0% found this document useful (0 votes)
4 views15 pages

Unit 3 Notes

Inheritance in PHP allows a child class to inherit properties and methods from a parent class, promoting code reusability and structure. PHP supports single, multilevel, and hierarchical inheritance, while multiple inheritance can be simulated using interfaces and traits. Polymorphism, method overloading, abstract classes, interfaces, and traits are advanced OOP features that enhance flexibility and functionality in PHP programming.

Uploaded by

kaidfockshg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views15 pages

Unit 3 Notes

Inheritance in PHP allows a child class to inherit properties and methods from a parent class, promoting code reusability and structure. PHP supports single, multilevel, and hierarchical inheritance, while multiple inheritance can be simulated using interfaces and traits. Polymorphism, method overloading, abstract classes, interfaces, and traits are advanced OOP features that enhance flexibility and functionality in PHP programming.

Uploaded by

kaidfockshg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Inheritance in PHP

Inheritance is a key feature of Object-Oriented Programming (OOP) in PHP that allows a class
(child class) to inherit properties and methods from another class (parent class). This helps in
code reusability and hierarchy structuring.

1. Basic Syntax
In PHP, inheritance is implemented using the extends keyword.
php
CopyEdit
<?php
// Parent class
class Animal {
public $name;

public function __construct($name) {


$this->name = $name;
}

public function makeSound() {


echo "Some generic animal sound";
}
}

// Child class (inherits from Animal)


class Dog extends Animal {
public function makeSound() {
echo $this->name . " barks!";
}
}

// Creating an object of the Dog class


$dog = new Dog("Buddy");
$dog->makeSound(); // Output: Buddy barks!
?>

2. Access Modifiers in Inheritance


 public → Accessible everywhere.
 protected → Accessible within the class and its subclasses.
 private → Only accessible within the class itself.
Example:
php
class ParentClass {
public $publicVar = "Public";
protected $protectedVar = "Protected";
private $privateVar = "Private";

public function showVars() {


echo "Inside Parent: " . $this->publicVar . ", " . $this->protectedVar
. ", " . $this->privateVar . "<br>";
}
}
class ChildClass extends ParentClass {
public function showInheritedVars() {
echo "Inside Child: " . $this->publicVar . ", " . $this-
>protectedVar . "<br>";
// echo $this->privateVar; // ERROR: Cannot access private property
}
}

$child = new ChildClass();


$child->showInheritedVars();
?>

Types of Inheritance in PHP


Inheritance in PHP allows a class (child) to inherit properties and methods from another class
(parent). PHP supports single inheritance but does not support multiple inheritance directly.
However, multiple inheritance can be simulated using interfaces and traits.

1. Single Inheritance (Supported in PHP)


In single inheritance, a child class inherits from a single parent class.
Diagram:
Parent Class

Child Class
Example:
php
CopyEdit
<?php
class Animal {
public function makeSound() {
echo "Animal makes a sound";
}
}

class Dog extends Animal {


public function bark() {
echo "Dog barks!";
}
}

$dog = new Dog();


$dog->makeSound(); // Output: Animal makes a sound
$dog->bark(); // Output: Dog barks!
?>

2. Multilevel Inheritance (Supported in PHP)


In multilevel inheritance, a class inherits from another class, which itself is inherited from
another class.
Diagram:
Grandparent Class

Parent Class

Child Class
Example:
<?php
class Animal {
public function eat() {
echo "Eating...";
}
}

class Mammal extends Animal {


public function breathe() {
echo "Breathing...";
}
}

class Dog extends Mammal {


public function bark() {
echo "Barking!";
}
}

$dog = new Dog();


$dog->eat(); // Output: Eating...
$dog->breathe(); // Output: Breathing...
$dog->bark(); // Output: Barking!
?>

3. Hierarchical Inheritance (Supported in PHP)


In hierarchical inheritance, multiple child classes inherit from a single parent class.
Diagram:
Parent Class
↓ ↓ ↓
Child1 Child2 Child3
Example:
php
CopyEdit
<?php
class Animal {
public function makeSound() {
echo "Animal makes a sound";
}
}

class Dog extends Animal {


public function bark() {
echo "Dog barks!";
}
}

class Cat extends Animal {


public function meow() {
echo "Cat meows!";
}
}
$dog = new Dog();
$dog->makeSound(); // Output: Animal makes a sound
$dog->bark(); // Output: Dog barks!

$cat = new Cat();


$cat->makeSound(); // Output: Animal makes a sound
$cat->meow(); // Output: Cat meows!
?>

4. Multiple Inheritance (Not Supported Directly, Can Be


Achieved Using Interfaces)
PHP does not support multiple inheritance directly, but we can achieve similar functionality
using interfaces.
Diagram:
Interface1 Interface2
↓ ↓
Class Implementing Both
Example:
<?php
interface Animal {
public function makeSound();
}

interface Pet {
public function beFriendly();
}

class Dog implements Animal, Pet {


public function makeSound() {
echo "Woof!";
}

public function beFriendly() {


echo "Wags tail!";
}
}

$dog = new Dog();


$dog->makeSound(); // Output: Woof!
$dog->beFriendly(); // Output: Wags tail!
?>

5. Hybrid Inheritance (Not Supported Directly, Can Be


Achieved Using Traits & Interfaces)
Hybrid inheritance is a mix of multiple and hierarchical inheritance. Since PHP does not support
multiple inheritance directly, we use traits to combine behaviors.
Diagram (Using Traits):
Trait1 Trait2
↓ ↓
Class Using Both
Example:
php
CopyEdit
<?php
trait CanFly {
public function fly() {
echo "Flying high!";
}
}

trait CanSwim {
public function swim() {
echo "Swimming in water!";
}
}

class Bird {
use CanFly;
}

class Fish {
use CanSwim;
}

$bird = new Bird();


$bird->fly(); // Output: Flying high!

$fish = new Fish();


$fish->swim(); // Output: Swimming in water!
?>

Summary Table
Type of Inheritance Supported in PHP? Description
Single Inheritance ✅ Yes One class inherits from another
Multilevel
✅ Yes A class inherits from another inherited class
Inheritance
Hierarchical
✅ Yes Multiple classes inherit from a single class
Inheritance
One class inherits from multiple classes (Not
Multiple Inheritance ❌ No (✅ Using Interfaces)
supported directly)
❌ No (✅ Using Traits &
Hybrid Inheritance A mix of multiple and hierarchical inheritance
Interfaces)

Polymorphism in PHP
Polymorphism is one of the key concepts of Object-Oriented Programming (OOP) that allows
objects of different classes to be treated as objects of a common superclass. In PHP,
polymorphism can be achieved using method overriding, interfaces, and abstract classes.

1. Method Overriding (Runtime Polymorphism)


When a child class provides a specific implementation of a method that is already defined in its
parent class, it's called method overriding.
Example:
php
CopyEdit
<?php
class Animal {
public function makeSound() {
echo "Some generic animal sound";
}
}

class Dog extends Animal {


public function makeSound() {
echo "Woof! Woof!";
}
}

class Cat extends Animal {


public function makeSound() {
echo "Meow! Meow!";
}
}

// Using polymorphism
$animals = [new Dog(), new Cat()];

foreach ($animals as $animal) {


$animal->makeSound();
echo "<br>";
}
?>
Output:
CopyEdit
Woof! Woof!
Meow! Meow!
Here, the makeSound() method is overridden in each subclass, allowing different behaviors.

2. Polymorphism with Abstract Classes


Abstract classes provide a base for polymorphism by forcing child classes to implement specific
methods.
Example:
php
CopyEdit
<?php
abstract class Animal {
abstract public function makeSound();
}

class Dog extends Animal {


public function makeSound() {
echo "Woof!";
}
}

class Cat extends Animal {


public function makeSound() {
echo "Meow!";
}
}

// Polymorphic behavior
function makeAnimalSound(Animal $animal) {
$animal->makeSound();
}

makeAnimalSound(new Dog()); // Output: Woof!


echo "<br>";
makeAnimalSound(new Cat()); // Output: Meow!
?>
Here, the makeAnimalSound() function accepts any Animal type, demonstrating polymorphism.

3. Polymorphism with Interfaces


An interface ensures that multiple classes implement the same method, allowing polymorphism.
Example:
php
CopyEdit
<?php
interface Shape {
public function calculateArea();
}

class Circle implements Shape {


private $radius;

public function __construct($radius) {


$this->radius = $radius;
}

public function calculateArea() {


return 3.14 * $this->radius * $this->radius;
}
}

class Rectangle implements Shape {


private $width, $height;

public function __construct($width, $height) {


$this->width = $width;
$this->height = $height;
}

public function calculateArea() {


return $this->width * $this->height;
}
}

// Polymorphic function
function printArea(Shape $shape) {
echo "Area: " . $shape->calculateArea() . "<br>";
}
printArea(new Circle(5)); // Output: Area: 78.5
printArea(new Rectangle(4, 5)); // Output: Area: 20
?>
Here, the printArea() function works with any object that implements the Shape interface.

5. Summary
Polymorphism
Description Example
Type
Method
Child class overrides a parent method makeSound() in Dog and Cat
Overriding
Abstract Classes Force child classes to implement methods Animal class with makeSound()
Allow multiple classes to follow the same Shape interface with
calculateArea()
Interfaces method structure

Method Overloading in PHP


Method Overloading is a feature in some object-oriented programming languages that allows
multiple methods with the same name but different parameters in a class.
However, PHP does not support method overloading in the traditional sense (like Java or C+
+). Instead, PHP allows overloading dynamically using magic methods like __call() and
__callStatic().

1. Method Overloading Using __call()


The __call() magic method allows handling calls to undefined or overloaded methods
dynamically.
Example:
<?php
class Demo {
public function __call($name, $arguments) {
echo "Method '$name' is called with arguments: " . implode(', ',
$arguments);
}
}

$obj = new Demo();


$obj->test(10, 20); // Output: Method 'test' is called with arguments: 10, 20
?>
Explanation:
 __call($name, $arguments) intercepts calls to non-existent methods.
 $name stores the method name.
 $arguments is an array of arguments passed.
2. Method Overloading Using __callStatic()
The __callStatic() magic method works for static methods that are not explicitly defined.
Example:
<?php
class StaticDemo {
public static function __callStatic($name, $arguments) {
echo "Static method '$name' called with arguments: " . implode(', ',
$arguments);
}
}

StaticDemo::show(100, 200); // Output: Static method 'show' called with


arguments: 100, 200
?>
Explanation:
 __callStatic($name, $arguments) intercepts calls to undefined static methods.

3. Overloading Using Default Parameters


Although PHP does not support method overloading directly, default parameters allow some
flexibility.
Example:
php
CopyEdit
<?php
class MathOperations {
public function add($a, $b = 0, $c = 0) {
return $a + $b + $c;
}
}

$obj = new MathOperations();


echo $obj->add(5); // Output: 5
echo "<br>";
echo $obj->add(5, 10); // Output: 15
echo "<br>";
echo $obj->add(5, 10, 20); // Output: 35
?>
Explanation:
 The method add() accepts different numbers of parameters.
 Default values allow simulating overloading.

5. Summary
Method Description
__call() Handles calls to undefined or overloaded instance methods
__callStatic() Handles calls to undefined or overloaded static methods
Default Parameters Simulates overloading by setting default values
Key Takeaways
✅ PHP does not support traditional method overloading.
✅ Overloading is handled dynamically using __call() and __callStatic().
✅ Default parameters and conditional logic can simulate method overloading.
✅ Overloading is useful for flexible function calls with varying parameters.
Advanced OOP Features in PHP
1. Abstract Classes
 Abstract classes cannot be instantiated.
 They force child classes to implement certain methods.
Example:
php
CopyEdit
<?php
abstract class Animal {
abstract public function makeSound();

public function sleep() {


echo "Sleeping...";
}
}

class Dog extends Animal {


public function makeSound() {
echo "Woof! Woof!";
}
}

$dog = new Dog();


$dog->makeSound(); // Output: Woof! Woof!
$dog->sleep(); // Output: Sleeping...
?>
Key Points:
✅ An abstract class can have both abstract and concrete methods.
✅ Child classes must implement all abstract methods.
2. Interfaces
 Interfaces define a contract that classes must follow.
 A class can implement multiple interfaces (unlike inheritance, which allows only one parent
class).
Example:
php
CopyEdit
<?php
interface Vehicle {
public function start();
}

interface Fuel {
public function refuel();
}

class Car implements Vehicle, Fuel {


public function start() {
echo "Car is starting...";
}
public function refuel() {
echo "Refueling the car...";
}
}

$myCar = new Car();


$myCar->start(); // Output: Car is starting...
$myCar->refuel(); // Output: Refueling the car...
?>
Key Points:
✅ Interfaces only define methods, they do not provide implementations.
✅ A class can implement multiple interfaces.
3. Traits (Multiple Inheritance Alternative)
 PHP does not support multiple inheritance.
 Traits allow code reuse across multiple classes.
Example:
php
CopyEdit
<?php
trait Logger {
public function log($message) {
echo "Logging message: $message";
}
}

class User {
use Logger;
}

class Order {
use Logger;
}

$user = new User();


$user->log("User logged in."); // Output: Logging message: User logged in.

$order = new Order();


$order->log("Order placed."); // Output: Logging message: Order placed.
?>
Key Points:
✅ Traits help reuse code across different classes.
✅ They act as a substitute for multiple inheritance.
Static Methods and Properties
 Static methods and properties belong to the class itself, not an instance.
 Accessed using ClassName::methodName().
Example:
<?php
class MathUtils {
public static function add($a, $b) {
return $a + $b;
}
}
echo MathUtils::add(10, 20); // Output: 30
?>
Key Points:
✅ No need to create an instance to call static methods.
✅ Cannot access $this inside static methods.
Late Static Binding (static::)
 Allows correct method resolution in hierarchical classes.
<?php
class A {
public static function who() {
echo __CLASS__;
}

public static function test() {


static::who(); // Late Static Binding
}
}

class B extends A {
public static function who() {
echo __CLASS__;
}
}

B::test(); // Output: B
?>
Key Points:
✅ self:: refers to the class where the method is defined.
✅ static:: refers to the class that calls the method.
Summary Table
Feature Description
Abstract Classes Enforce method implementation in child classes
Interfaces Define a contract for classes
Traits Allow code reuse across multiple classes
Static Methods Methods that belong to the class, not instances
Late Static Binding Uses static:: for correct method resolution

Type Hinting in PHP


Type hinting (or type declarations) in PHP allows us to specify the expected data types for
function arguments, return values, and class properties. This helps prevent type-related errors
and improves code readability, maintainability, and robustness.

1. Type Hinting for Function Arguments


Type hinting allows specifying the expected type for function parameters.
Example:
<?php
function greet(string $name) {
return "Hello, " . $name;
}

echo greet("John"); // Output: Hello, John


// echo greet(123); // ERROR: Argument must be of type string
?>
Allowed Types:
Type Description
int Integer
float Floating-point number
string Text/string
bool Boolean (true or false)
array Arrays
object Objects
callable A function/method reference
iterable Arrays and objects implementing Traversable
mixed (PHP 8) Any type (useful for flexibility)
static (PHP 8) The called class type

2. Type Hinting for Return Values


You can enforce a specific return type for functions.
Example:
php
CopyEdit
<?php
function add(int $a, int $b): int {
return $a + $b;
}

echo add(5, 10); // Output: 15


?>
Key Points:
✅ The : int return type ensures the function always returns an integer.
✅ If a different type is returned, PHP throws a TypeError.
3. Type Hinting with Objects (Class Type Hinting)
You can specify a class type as an argument type.
Example:
php
CopyEdit
<?php
class User {
public $name;
public function __construct(string $name) {
$this->name = $name;
}
}

function printUser(User $user) {


echo "User: " . $user->name;
}

$user = new User("Alice");


printUser($user); // Output: User: Alice
?>
Key Points:
✅ Only instances of User class can be passed.
✅ If a different type is passed, PHP throws a TypeError.

4. Type Hinting for Arrays


You can restrict array elements to a specific type using array type hinting.
Example:
php
CopyEdit
<?php
function processNumbers(array $numbers) {
foreach ($numbers as $num) {
echo $num * 2 . " ";
}
}

processNumbers([1, 2, 3]); // Output: 2 4 6


?>
✅ Only an array can be passed.
✅ Trying to pass a non-array value will result in an error.

5. Type Hinting with Interfaces & Abstract Classes


Since PHP allows interface and abstract class type hinting, functions can enforce specific
contracts.
Example:
php
CopyEdit
<?php
interface Vehicle {
public function move();
}

class Car implements Vehicle {


public function move() {
echo "Car is moving";
}
}

function drive(Vehicle $v) {


$v->move();
}

$car = new Car();


drive($car); // Output: Car is moving
?>
✅ Only objects implementing Vehicle can be passed.
✅ This enforces the interface contract.

You might also like