Saturday, 20 December 2014

Difference between overloading and overriding in php with Example

Difference between overloading and overriding in php with Example


Overloading: In Real world, overloading means assigning some extra stuff to someone. As as in real world Overloading in PHP means calling extra functions.
Example of Overloading:
class testclass {
    public $_data;
    public function __get($name) {
        echo "Getting '$name'\n ";
        return $this->data[$name];
    }
}

$obj = new testclass();
/** Magic method Example * */
echo $obj->a; //As __get function called - Overloading example 2
/** Magic method Example * */ 

We can do overloading with magic methods and are following:
__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo()



Overriding: In Real world, Overriding means changing the parental behaviour in Child. As as in real world Overriding in PHP means calling of child function instead of parent function, both class's function have same name.
Example of Overriding:
class parentclass {
    function name() {
        return 'Parent';
    }
}

class childclass extends parentclass {
    function name() {
        return 'Child';
    }
}

$obj = new childclass();
echo $obj->name();//It called child function instead of parent parent function - Overriding Example


3 comments :

Kamal Hasija said...

I don't understand this code
class testclass {
public $_data;
public function __get($name) {
echo "Getting '$name'\n ";
return $this->data[$name];
}
}

$obj = new testclass();
/** Magic method Example * */
echo $obj->a; //As __get function called - Overloading example 2
/** Magic method Example * */

any body please help me to get out from this. Please give me a perfect solution with proper explanation of every line, classes, instances, methods and data members.

Raj Dhanki said...

data['$name'];


}

}
$obj = new testClass(); // create object

echo $obj ->name = " Raj Dhanki"; // we have to use the parameter that we want to print in screen like name so we call name parameter that is inside the __get() magic method and as per magic method calls automatically.. and we have given string to name property by getting its value....
hope this will be useful i think so...





?>

Barshan Hassan said...

But Sir After overriding can we call parent Class function with child object???
Like in c++ we can access using scope resulation operator ::
please reply must
For example as u give
$obj = New childclass;
$obj->name();
it should be return 'Parent'
how this is possible?????

Post a Comment