Hi I'm very new at PHP and wanted to know if you can store a function in a Class Property and then call it later.
class Route
{
public $handler;
//$handler is a reference to a function that I want to store and call later
function __construct($handler)
{
$this->handler = $handler;
//or maybe something like
//$this->handler = fn () => $handler();
//this works fine
$handler();
/*I get why this does not work since $handler is not a
method of this class but how would I store a function
and be able to call it later in a different context?*/
$this->handler();
}
}
How would I do something like this?
function foo()
{
echo "success";
}
$route = new Route('foo');
$route->$handler();
CodePudding user response:
Use brackets when calling your property stored callable:
class Route
{
public $handler;
public function __construct(callable $handler) {
$this->handler = $handler;
}
}
$handler = static fn() => var_dump('Works');
$obj = new Route($handler);
($obj->handler)();
then
$ php test.php
string(5) "Works"
PS: I recommend to always use type hints.
CodePudding user response:
I hope the code below helps.
class Route
{
public $handler;
function __construct($handler)
{
$this->handler = $handler;
}
}
function foo()
{
echo "success";
}
$route = new Route('foo');
/* There is problem to call a function that is a class property. */
/* You may use a temporary variable. */
$function = $route->handler;
$function();