[英]How to call function stored in Class property in PHP
嗨,我是 PHP 的新手,想知道您是否可以將 function 存儲在 Class 屬性中,然后稍后調用它。
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();
}
}
我會怎么做這樣的事情?
function foo()
{
echo "success";
}
$route = new Route('foo');
$route->$handler();
在調用存儲的可調用屬性時使用方括號:
class Route
{
public $handler;
public function __construct(callable $handler) {
$this->handler = $handler;
}
}
$handler = static fn() => var_dump('Works');
$obj = new Route($handler);
($obj->handler)();
然后
$ php test.php
string(5) "Works"
PS:我建議始終使用類型提示。
我希望下面的代碼有所幫助。
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.