Re: Add methods to object dinamically

From: Date: Tue, 26 Oct 2004 17:36:32 +0000
Subject: Re: Add methods to object dinamically
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-200375@lists.php.net to get a copy of this message
* Francisco M. Marzoa Alonso <fmmarzoa@gmx.net>: > 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; No. There are some things you can look into, however. PHP4 has an overload() function (and PHP5 has it built in) -- you could then add a __call() method that checks to see if a function is defined, and if so, calls it. class MyClass { var $a; // Note: you'd call this differently in PHP5 function __call($function, $arguments, &$return) { if (function_exists($function)) { $function($arguments); } } } overload('MyClass'); // This line unncessary in PHP5 The other possibility is to look into the classkit extension (http://php.net/classkit); this would require being able to install PHP extensions (not a problem if it's your own box). -- Matthew Weier O'Phinney | mailto:matthew@garden.org Webmaster and IT Specialist | http://www.garden.org National Gardening Association | http://www.kidsgardening.com 802-863-5251 x156 | http://nationalgardenmonth.org

« previous php.general (#200375) next »