Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new method to a php object on the fly?

Tags:

methods

php

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() 
like image 442
MadBad Avatar asked May 30 '10 08:05

MadBad


People also ask

What is __ method __ in PHP?

"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.

How do you create a new object in PHP?

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.

How do you declare an object variable in PHP?

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.


1 Answers

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(); 
like image 163
karim79 Avatar answered Oct 03 '22 03:10

karim79