Calling anonymous functions defined as object variables in php

I have php code like:

class Foo { public $anonFunction; public function __construct() { $this->anonFunction = function() { echo "called"; } } } $foo = new Foo(); //First method $bar = $foo->anonFunction(); $bar(); //Second method call_user_func($foo->anonFunction); //Third method that doesn't work $foo->anonFunction(); 

Is there a way in php that I can use a third method to call anonymous functions defined as properties of a class?

thanks

+4
source share
1 answer

Not directly. $foo->anonFunction(); does not work because PHP will try to directly call the method on this object. It will not check if a property of the name that stores the called exists. You can intercept the method call though.

Add this to the class definition

  public function __call($method, $args) { if(isset($this->$method) && is_callable($this->$method)) { return call_user_func_array( $this->$method, $args ); } } 

This method is also explained in

+9
source

Source: https://habr.com/ru/post/1347357/


All Articles