Since PHP 5.3 supports locking, you can dynamically define instance methods as variables that hold closures:
$class->foo = function (&$self, $n) { print "Current \$var: " . $self->var . "\n"; $self->var += $n; print "New \$var: " .$self->var . "\n"; };
By taking $self (you cannot use $this context of an external object) as a reference ( & ), you can change the instance.
However, trying to call a function usually causes problems:
$class->foo(2);
You get a fatal error. PHP considers foo to be a $class method, because of the syntax. In addition, you must pass the instance as the first argument.
Fortunately, there is a special function for calling functions called call_user_func :
call_user_func($class->foo, &$class, 2);
Remember to put & in front of the instance variable.
Even simpler if you use the __call magic method:
class MyClass { public function __call ($method, $arguments) { if (isset($this->$method)) { call_user_func_array($this->$method, array_merge(array(&$this), $arguments)); } } }
Now you can call $class->foo(2) . The __call magic method catches an invocation of an unknown method and causes a closure in the variable $class->foo with the same name as the called method.
Of course, if $class->var was closed, closing in the $class->foo variable stored in the variable could not access it.
jocap Nov 05 2018-11-11T00: 00Z
source share