是否可以以这种方式添加方法/功能,例如
$arr = array(
"nid"=> 20,
"title" => "Something",
"value" => "Something else",
"my_method" => function($arg){....}
);
或者像这样
$node = (object) $arr;
$node->my_method=function($arg){...};
如果可能的话,我该如何使用该功能/方法?
这现在可以在 PHP 7.1 中使用匿名类来实现
$node = new class {
public $property;
public function myMethod($arg) {
...
}
};
// and access them,
$node->property;
$node->myMethod('arg');
您不能动态地将方法添加到 stdClass 并以正常方式执行它。但是,您可以做一些事情。
在您的第一个示例中,您正在创建一个闭包。您可以通过发出以下命令来执行该闭包:
$arr['my_method']('Argument')
您可以创建一个 stdClass 对象并为其属性之一分配一个闭包,但由于语法冲突,您不能直接执行它。相反,您必须执行以下操作:
$node = new stdClass();
$node->method = function($arg) { ... }
$func = $node->method;
$func('Argument');
尝试
$node->method('Argument')
会产生错误,因为 stdClass 上不存在方法“方法”。
从 PHP 7 开始,也可以直接调用匿名函数属性:
$obj = new stdClass;
$obj->printMessage = function($message) { echo $message . "\n"; };
echo ($obj->printMessage)('Hello World'); // Hello World
这里的表达式$obj->printMessage产生匿名函数,然后直接使用参数执行'Hello World'。然而,在调用它之前必须将函数表达式放在括号中,这样以下操作仍然会失败:
echo $obj->printMessage('Hello World');
// Fatal error: Uncaught Error: Call to undefined method stdClass::printMessage()
另一种解决方案是创建一个匿名类并通过魔术函数代理调用__call,使用箭头函数,您甚至可以保持对上下文变量的引用:
new Class ((new ReflectionClass("MyClass"))->getProperty("myProperty")) {
public function __construct(ReflectionProperty $ref)
{
$this->setAccessible = fn($o) => $ref->setAccessible($o);
$this->isInitialized = fn($o) => $ref->isInitialized($o);
$this->getValue = fn($o) => $ref->getValue($o);
}
public function __call($name, $arguments)
{
$fn = $this->$name;
return $fn(...$arguments);
}
}
class myclass {
function __call($method, $args) {
if (isset($this->$method)) {
$func = $this->$method;
return call_user_func_array($func, $args);
}
}
}
$obj = new myclass();
$obj->method = function($var) { echo $var; };
$obj->method('a');
或者您可以创建默认类并使用...