Re: Add methods to object dinamically

From: Date: Tue, 26 Oct 2004 17:44:05 +0000
Subject: Re: Add methods to object dinamically
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-200376@lists.php.net to get a copy of this message
Francisco M. Marzoa Alonso wrote:
I've seen that's possible to add members to objects dinamically, in example: class MyClass { private $a; } $MyObject = new MyClass (); $MyObject->b = 1; Now $MyObject has a public member called 'b' that has a value of '1'. The question is, is it possible to add methods in the same way? I meant something such as: function sum ( $this ) { return $this->a+$this->b; } $MyObject->sum = sum; Note that code will not work, but it illustrates what I'm asking for.
Sort of :) In PHP5, this will work. <?php class DoesStuff {
    private $_methods = array();
    public function __call($method, $params)
    {
        if (isset($this->_methods[$method])) {
            $call = $this->_methods[$method];
            return $call($this);
        }
    }
    public function __set($var, $value)
    {
        if (is_string($value) && is_callable($value)) {
            $this->_methods[$var] = $value;
        } else {
            $this->$var = $value;
        }
    }
} function test($o) {
    return $o->val;
} $o = new DoesStuff; $o->val = 4; $o->test = 'test'; echo $o->test(); ?> However, you won't have access to private or protected data members. It is always better to rigidly define your methods, and extend the class as someone else suggested. Greg

« previous php.general (#200376) next »