Tuesday, November 25, 2008

Initializing objects from other objects in PHP

Sometimes we need to initialize an object based on another object. Typically, if we have a class MyClass and subclass MyExtendedClass with some additional functionality, we may need to turn a MyClass object into a MyExtendedClass object. How to do that easily in PHP?


In OOP generally, that is handled by a second constructor, which takes the source object as an argument, initializes the extended object and then copies the properties. In PHP there is only one constructor allowed, but the additional constructor may be simulated by a static method. Additionally, the copying of the properties may be handled by appropriate export/import methods.

class MyClass
{
    protected $_foo = '';                
    public $bar = '';            
 
 
    public function __construct($foo = '', $bar = '') 
    {
        $this->_foo = $foo; 
        $this->bar = $bar;
    }
    
    
    protected function _export()
    {
        $properties = array();
        foreach ($this as $name => $value) {
            $properties[$name] = $value;
        }
        return $properties;
    }
}


class MyExtendedClass extends MyClass
{

    static public function createFromObject(MyClass $obj)
    {
        $extObj = new MyExtendedClass();
        $extObj->_import($obj);
        return $extObj;
    }
    
    
    private function _import(MyClass $obj)
    {
        foreach ($obj->_export() as $name => $value) {
            $this->$name = $value;
        }
    }
    
}

$object = new MyClass('one', 'two');
$extendedObject = MyExtendedClass::createFromObject($object);

var_dump($object);
var_dump($extendedObject);

No comments:

Post a Comment