简体   繁体   English

如何调用PHP中存储在Class属性中的function

[英]How to call function stored in Class property in PHP

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.嗨,我是 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();
  }
}

How would I do something like this?我会怎么做这样的事情?

function foo()
{
  echo "success";
}

$route = new Route('foo');
$route->$handler();

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. PS:我建议始终使用类型提示。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM