add method/function in instance of stdClass in instance context for using $this in PHP?

316 views Asked by At

How add function to instance object of stdClass?

$obj = (object)['name' => 'test', 'x' => 0];
$obj->move = function() { $this->x++; return $this->x; };
var_dump(($obj->move)());

I try use closure to simulate method, there is another way to directly add dynamicly a function to my object?

For my exemple, there is an error :

Fatal error: Uncaught Error: Using $this when not in object context

so how keep object context, for use $this in my closure ?

I try add use($obj) but error stay... (normal)

So how can I do ?

0

There are 0 answers