gpt4 book ai didi

php - 在 "anonymous"对象中使用 $this

转载 作者:可可西里 更新时间:2023-11-01 00:42:25 24 4
gpt4 key购买 nike

我正在使用以下类来模拟 PHP 中的匿名对象:

class AnonymousObject
{
protected $methods = array();

public function __construct(array $options) {
$this->methods = $options;
}

public function __call($name, $arguments) {
$callable = null;
if (array_key_exists($name, $this->methods))
$callable = $this->methods[$name];
elseif(isset($this->$name))
$callable = $this->$name;

if (!is_callable($callable))
throw new BadMethodCallException("Method {$name} does not exist");

return call_user_func_array($callable, $arguments);
}
}

( https://gist.github.com/Mihailoff/3700483 )

现在,只要声明的函数独立存在,一切正常,但每当我尝试像这样从另一个函数调用一个函数时......

$anonymous = new AnonymousObject(array(
"foo" => function() { $this->bar(); },
"bar" => function() { }
));

当然我会得到 Fatal error: Using $this when not in object context

有什么办法可以解决这个问题吗?

最佳答案

您可以使用 bind() 或 bindTo() method代表匿名函数的 Closure 实例。

<?php
class AnonymousObject
{
protected $methods = array();

public function __construct(array $options) {
$this->methods = $options;
}

public function __call($name, $arguments) {
$callable = null;
if (array_key_exists($name, $this->methods))
$callable = $this->methods[$name];
elseif(isset($this->$name))
$callable = $this->$name;

if (!is_callable($callable))
throw new BadMethodCallException("Method {$name} does not exists");

$callable = $callable->bindTo($this);
return call_user_func_array($callable, $arguments);
}
}

$anonymous = new AnonymousObject(array(
"foo" => function() { echo 'foo'; $this->bar(); },
"bar" => function() { echo 'bar'; }
));

$anonymous->foo();

(示例不太正确,因为它只适用于匿名函数;不适用于所有其他 callable() 替代方案,例如 $this->name 部分)

打印foobar

关于php - 在 "anonymous"对象中使用 $this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31367735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com