21

是否可以以这种方式添加方法/功能,例如

$arr = array(
    "nid"=> 20,
    "title" => "Something",
    "value" => "Something else",
    "my_method" => function($arg){....}
);

或者像这样

$node = (object) $arr;
$node->my_method=function($arg){...};

如果可能的话,我该如何使用该功能/方法?

4

5 回答 5

28

这现在可以在 PHP 7.1 中使用匿名类来实现

$node = new class {
    public $property;

    public function myMethod($arg) { 
        ...
    }
};

// and access them,
$node->property;
$node->myMethod('arg');
于 2017-09-20T15:02:53.287 回答
19

您不能动态地将方法添加到 stdClass 并以正常方式执行它。但是,您可以做一些事情。

在您的第一个示例中,您正在创建一个闭包。您可以通过发出以下命令来执行该闭包:

$arr['my_method']('Argument')

您可以创建一个 stdClass 对象并为其属性之一分配一个闭包,但由于语法冲突,您不能直接执行它。相反,您必须执行以下操作:

$node = new stdClass();
$node->method = function($arg) { ... }
$func = $node->method;
$func('Argument');

尝试

$node->method('Argument')

会产生错误,因为 stdClass 上不存在方法“方法”。

使用魔术方法__call ,请参阅此SO 答案,了解一些巧妙的黑客行为。

于 2013-07-09T01:50:56.787 回答
7

从 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()
于 2019-07-13T15:36:44.750 回答
0

另一种解决方案是创建一个匿名类并通过魔术函数代理调用__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);
            }

    }
于 2020-04-30T16:27:46.500 回答
0
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');

或者您可以创建默认类并使用...

于 2021-07-21T14:48:27.177 回答