What is function overriding vs overloading in php oops

Object Oriented Programming

Posted on 20 Jun 15 by Vickey
  2824



Function Overriding

In the sence of Overriding is to replace parent property in child.In Overriding if we have defined a function in base class and we want to change the
its basic functionality in child class then we can do this and this is called function Overriding for example

class BaseController {
{
    public function dbConnection(){

        $host = "localhost";
        $username = "root";
        $password = "root";
        $connection = new mysqli($host, $username, $password);

    }
}



class UsersController extends BaseController {

    public function dbConnection(){

        $host = "192.168.2.00";
        $username = "root";
        $password = "PASSWORD123";
        $connection = new mysqli($host, $username, $password);

    }
}

as you cann see in base class i have a method dbConnection with code for make database connection but in child class
i have change the host and password for database connection

Function Overloading

In programming the function Overloading means is create two function with same name with different functionality by passing different arguments.
but in php we can not create two function with the same name so if we want to implement overloading in php we can take help of _call function
Here is a simple example of function overloading by using of _call function

class Calculate{

    public function __call($name, $arguments){

        if($name='sum'){

            if(count($arguments) === 2 ){
                return $this->sum1($arguments[0],$arguments[1]);
            }
            if(count($arguments) === 3){
                return $this->sum2($arguments[0], $arguments[1],$arguments[2]);
            }
        }
    }
    public function sum1($a,$b){
        echo $a+$b;
    }

    public function sum2($a,$b,$c){
        echo $a+$b+$c;
    }

}
$obj=new Calculate();
echo $obj->sum(1,2);
echo "
";
echo $obj->sum(1,2,3);

here _call magic function manage the overloading by calling different function on basis of number of arguments


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com