Overriding in php classes

Overloading and overriding in PHP

Overloading and overriding method is very useful feature of any object oriented programming language. In this section we will discuss how to implement method overloading and overriding in PHP. In object oriented programming concept if methods of the class has the same name but different in parameters are termed as overloading and if the methods of the class are same as well as parameter then it is termed as overriding

What is method overloading in PHP?

Function overloading is a feature of object oriented programming that allows creating methods with the same name but differ in the type of input parameter. In other words, we can say that functions are used to perform different tasks. Overloading in object oriented programming is same as real word overloading. In real world, method overloading means to assign extra work to same person. In programming language, you are asking method to do some extra work or some different work.

Overloading in PHP creates properties and methods dynamically. These dynamic properties and method are processes using magic method.

How to implement overloading in PHP?

Following is an example which shows how two function with same name works in PHP:

class text public function display($parameter1) echo "Hello world!!"; 
>
public function display($parameter1,$parameter2) echo "Hello India!!”;
>>
$obj = new text;
$obj->display('Hello'); // It will show fatal error
?>

Fatal error: Cannot redeclare text::display()

Читайте также:  Java map string to function

As from above example we can say that in PHP overloading with same name function can’t be possible. Therefore, with the help of magic function overloading is done in PHP.

Following is an example of overloading with the help of magic methods:

class TDshape const Pi = 3.142 ; // constant value 
function __call($fname, $argument) < if($name == 'area')
switch(count($argument)) < case 0 : return 0 ;
case 1 : return self::Pi * $argument[0] ; // 3.14 * 5
case 2 : return $argument[0] * $argument[1]; // 5 * 10
>
>
>
$circle = new TDshape();
echo "Area of circle:".$circle->area(5)."
"; // display the area of circle
$rect = new TDshape();
echo "Area of rectangle:".$rect->area(5,10); // display area of rectangle
?>
Area of circle:15.71 Area of rectangle:50

In the above example __call is a magic method. This method is automatically called behind the scene.

What is method overriding in PHP?

In object oriented programming overriding is to replace parent method in child class.In overriding you can re-declare parent class method in child class. So, basically the purpose of overriding is to change the behavior of your parent class method.

When your class has some method and another class(derived class) want the same method with different behavior then using overriding you can completely change the behavior of base class(or parent class). The two methods with the same name and same parameter is called overriding.

How to implement overriding in PHP?

Overriding concept is very easy in PHP. As we all know overriding in PHP is a method of updating the inherited method from parent class to child class. So, in this case you will require method with same name in parent class as well as in child class and then we will see how the behavior of parent class method is changed when child class override the method of parent class.

Following is an example of overriding in PHP:
  class parent_class    public function text() //text() is a parent class method   echo "Hello!! everyone I am parent class text method"."
";
> public function test() echo "Hello!! I am second method of parent class"."
";
> > class child extends parent_class public function text() // Text() parent class method which is override by child class echo "Hello!! Everyone i am child class"; > > $obj= new parent_class(); $obj->text(); // display the parent class method echo $obj= new parent_class(); $obj->test(); $obj= new child(); $obj->text(); // display the child class method echo ?>
Hello!! Everyone I am parent class text method Hello!! I am second method of parent class Hello!! everyone i am child class

As from the above example we can see how text() method of parent class is overridden by child class.

Источник

PHP Override Method

Summary: in this tutorial, you will learn about the PHP overriding method and how to apply it effectively in your script.

Introduction to the PHP overriding method

Method overriding allows a child class to provide a specific implementation of a method already provided by its parent class.

To override a method, you redefine that method in the child class with the same name, parameters, and return type.

The method in the parent class is called overridden method, while the method in the child class is known as the overriding method. The code in the overriding method overrides (or replaces) the code in the overridden method.

PHP will decide which method (overridden or overriding method) to call based on the object used to invoke the method.

  • If an object of the parent class invokes the method, PHP will execute the overridden method.
  • But if an object of the child class invokes the method, PHP will execute the overriding method.

Let’s take an example to understand method overriding better.

The following example defines the Robot class that has one public method greet() and the Android class that inherits the Robot class:

 class Robot < public function greet() < return 'Hello!'; > > class Android extends Robot  Code language: HTML, XML (xml)

When you call the greet() method via the Android’s instance, PHP calls the greet() method of the Robot class:

 $android = new Android(); echo $android->greet(); // Hello!Code language: HTML, XML (xml)

This is a typical inheritance scenario.

Sometimes, you want to completely replace the method’s behavior of the parent class with a new one. In this case, you need to override the method of the parent class.

To override a method, you redefine the method in the parent class again in the child class but use a different logic.

The following adds the greet() method to the Android class that returns a different greeting message:

 class Robot < public function greet() < return 'Hello!'; > > class Android extends Robot < public function greet() < return 'Hi'; > > $robot = new Robot(); echo $robot->greet(); // Hello $android = new Android(); echo $android->greet(); // Hi!Code language: HTML, XML (xml)
  • First, invoke the greet() method of an instance of the Robot class, the greet() method in the Robot class executes.
  • Second, call the greet() method of an instance of the Android class, the greet() method in the Android class executes.

The following class diagram illustrates the relationship between the Robot and Android classes:

Call the overridden method in the overriding method

When you override a method, you will have two versions of the same method: one in the parent class and the other in the child class.

If you call the method of the parent class in the method in the child class, you cannot use $this keyword like this:

 class Android extends Robot < public function greet() < $greeting = $this->greet(); return $greeting . ' from Android.'; > >Code language: HTML, XML (xml)

The $this->greet() will call itself indefinitely.

To call the greet() method of the Robot class, you need to use the parent with the scope resolution operator (:: ) like the following:

 class Android extends Robot < public function greet() < $greeting = parent::greet(); return $greeting . ' from Android.'; > >Code language: HTML, XML (xml)

In this example, the greet() method in the Andoird class calls the greet() method of the Robot class. It concatenates the string returned by the greet() method of the Robot method with a literal string ‘ from Android.’ and returns the concatenated string.

More on PHP overriding method

Suppose that you need to define a new CheckingAccount class that extends the BankAccount class. The following defines the BankAccount class:

 class BankAccount < private $balance; public function __construct($amount) < $this->balance = $amount; > public function getBalance() < return $this->balance; > public function deposit($amount) < if ($amount > 0) < $this->balance += $amount; > return $this; > public function withdraw($amount) < if ($amount > 0 && $amount $this->balance) < $this->balance -= $amount; return true; > return false; > >Code language: HTML, XML (xml)

The withdraw() method checks if the withdrawal amount is greater than zero and less than or equal to the current balance before deducting it from the balance.

Second, define the CheckingAccount class that inherits the BankAccount class. The CheckingAccount class also has the withdraw() method that overrides the withdraw() method of the BankAccount class:

 class CheckingAccount extends BankAccount < private $minBalance; public function __construct($amount, $minBalance) < if ($amount > 0 && $amount >= $minBalance) < parent::__construct($amount); $this->minBalance = $minBalance; > else < throw new InvalidArgumentException('amount must be more than zero and higher than the minimum balance'); > > public function withdraw($amount)  < $canWithdraw = $amount >0 && $this->getBalance() - $amount > $this->minBalance; if ($canWithdraw) < parent::withdraw($amount); return true; > return false; > >Code language: HTML, XML (xml)

The withdraw() method in the CheckingAccount class checks the withdrawal amount against the minimum balance before deducting it.

The following class diagram illustrates the relationship between the BankAccount and CheckingAccount classes:

The final method

To prevent the method in the child class from overriding the method in the parent class, you can prefix the method with the final keyword:

public final function methodName() < //. >Code language: PHP (php)

The following adds the id() method to the Robot class:

class Robot < public function greet() < return 'Hello!'; > final public function id() < return uniqid(); > >Code language: PHP (php)

If you attempt to override the id() method from the Android class, you’ll get an error. For example:

class Android extends Robot < public function greet() < $greeting = parent::greet(); return $greeting . ' from Andoid.'; > public function id() < return uniqid('Android-'); > >Code language: PHP (php)
Cannot override final method Robot::id()Code language: PHP (php)

Summary

  • Method overriding allows a child class to define a method that overrides (or replaces) the method already provided by its parent class.
  • Use parent:: to call the overridden method in the overriding method.
  • Use the final method when you don’t want a child class’s method to override a parent class’s method.

Источник

Оцените статью