Tuesday, March 2, 2010

Extending objects in PHP at run-time :: Base Object :: Part 4

So, on our quest to add JavaScript flexibility to PHP we need another thing common in many JS frameworks: ability to extend objects at run time.

This is super easy based on what we have already done.
Add this method to your class Object:

public function extend(Object $oAnotherObject) {
        $this->_aProperties = array_merge(
            $this->_aProperties, 
            $oAnotherObject->_aProperties
        );
    }

Now you can copy dynamic methods and properties from Object to Object at run time like so:

$o1 = Object::construct();
    $o1->method1 = function($owner) { return 'method1'; };
    $o2 = Object::construct();
    $o2->method2 = function($owner) { return 'method2'; };
    $o2->extend($o1);
    print $o2->method1(); // output: method1
    print $o2->method2(); // output: method2

No comments: