0

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 ?

12
  • I don't think you can do this. See stackoverflow.com/questions/12868066/… for how to create a method in the class dynamically. Commented Jul 13, 2022 at 22:39
  • Is there a reason why you don't create a class? Commented Jul 13, 2022 at 22:39
  • @ManuelGuzman yes, I put it in my exemple. My data is an array at the begining, and there is a cast to object (I can't change this in real case) Commented Jul 13, 2022 at 22:41
  • 1
    $obj->move = Closure::fromCallable(function() { $this->x++; return $this->x; })->bindTo($obj); Commented Jul 13, 2022 at 22:51
  • 1
    Also fromCallable is unnecessary. You can just do $obj->move = (function() { $this->x++; return $this->x; })->bindTo($obj); Commented Jul 13, 2022 at 23:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.