【问题标题】:Assigning a function to a property of a class将函数分配给类的属性
【发布时间】:2016-04-13 17:09:33
【问题描述】:

我正在尝试做类似于PHP anonymous function assigned to class property in constructor is always null? 的事情,但我的解决方案似乎更简单。我想从 Stack Overflow Hot Shots 获得有关此解决方案的 cmets 以及是否有更好的解决方案。这是一个“最佳实践”的问题。

我想将一个函数(匿名或已定义)传递给一个类/对象,并能够稍后调用该函数。我从这个开始:

function Foo($arg) {return sprintf('In Foo(%s)',$arg);}
function Bar($arg) {return sprintf('In Bar(%s)',$arg);}

class TestIt {
  private $func;

  public function __construct( $func ) { $this->func = $func; }

  public function OutPut($arg) {
    return $this->func($arg);
  }
}

$test  = new TestIt('Foo');
echo $test->OutPut('Bozo');

运行时,我收到一个错误,指出方法 $this->func 不存在。如果我在方法OutPut() 中放置is_callable 测试,我发现$this->func 实际上是可调用的,但错误仍然存​​在。

但是,如果我使用 is_callable 的第三个参数,我可以正常工作。

public function OutPut($arg) {
  return is_callable($this->func,false,$tmpfunc) ? $tmpfunc($arg) : null;
}

这如何作为解决方案叠加起来?很好奇你的想法。

【问题讨论】:

  • __construnt 只是您的问题中的错字还是您的代码中也有?

标签: php function class


【解决方案1】:

因为没有办法让 PHP 将 $this->func() 解析为变量函数,所以这里有两种选择:

return call_user_func_array($this->func, array($arg));

或者:

$func = $this->func;
return $func($arg);

is_callable() 将返回静态方法调用someClass::someMethod,即使它不是静态方法并且在对象范围内调用。

【讨论】:

  • 谢谢。我更喜欢使用 call_user_func_array 的解决方案或使用 is_callable 的解决方案来进行错误检查。这两种解决方案之间会有性能差异吗?
  • 您可以进行基准测试,但我希望 is_callable 的开销稍大一些,并且可调用名称始终是静态名称(参见编辑)。
猜你喜欢
  • 2011-09-22
  • 1970-01-01
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 2021-04-07
  • 1970-01-01
相关资源
最近更新 更多