1

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 ?

Matrix
  • 3,458
  • 6
  • 40
  • 76
  • I don't think you can do this. See https://stackoverflow.com/questions/12868066/dynamically-create-php-class-functions for how to create a method in the class dynamically. – Barmar Jul 13 '22 at 22:39
  • Is there a reason why you don't create a class? – Manuel Guzman Jul 13 '22 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) – Matrix Jul 13 '22 at 22:41
  • https://stackoverflow.com/questions/52701638/how-to-bind-this-to-a-php-function – gre_gor Jul 13 '22 at 22:47
  • @gre_gor how you use this in my exemple? I need use `$obj->move` not `Closure::bind(...)` each time I want invoke my mathod – Matrix Jul 13 '22 at 22:51
  • 1
    `$obj->move = Closure::fromCallable(function() { $this->x++; return $this->x; })->bindTo($obj);` – gre_gor Jul 13 '22 at 22:51
  • @gre_gor nice ! it's that :) can you add an anwser ? I valid it ;) – Matrix Jul 13 '22 at 22:53
  • Since it's closed I can't. Maybe the dupe target should just be changed. – gre_gor Jul 13 '22 at 23:00
  • 1
    Also `fromCallable` is unnecessary. You can just do `$obj->move = (function() { $this->x++; return $this->x; })->bindTo($obj);` – gre_gor Jul 13 '22 at 23:00
  • I find this, it's exacly what you said, thx :) https://stackoverflow.com/questions/36998807/php-override-function-of-a-single-instance – Matrix Jul 13 '22 at 23:05
  • @gre_gor I make this global function `function addMethodToObject($obj, $func_name, $func) { $obj->{$func_name} = $func->bindTo($obj); }`, but how an I override stdClass for direcly do `$obj->addMethod('move', function(){...})` instead ? – Matrix Jul 13 '22 at 23:25
  • Just add it to the object the same way? – gre_gor Jul 14 '22 at 03:45

0 Answers0