How do I add a new method to an object "on the fly"?
$me= new stdClass; $me->doSomething=function () { echo 'I\'ve done something'; }; $me->doSomething(); //Fatal error: Call to undefined method stdClass::doSomething()
"Method" is basically just the name for a function within a class (or class function). Therefore __METHOD__ consists of the class name and the function name called ( dog::name ), while __FUNCTION__ only gives you the name of the function without any reference to the class it might be in.
To create an Object in PHP, use the new operator to instantiate a class. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.
The object variable is declared by using the new keyword followed by the class name. Multiple object variables can be declared for a class. The object variables are work as a reference variable.
You can harness __call
for this:
class Foo { public function __call($method, $args) { if (isset($this->$method)) { $func = $this->$method; return call_user_func_array($func, $args); } } } $foo = new Foo(); $foo->bar = function () { echo "Hello, this function is added at runtime"; }; $foo->bar();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With