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