在php中的std对象中添加方法 [英] Add method in an std object in php
问题描述
是否可以通过这种方式添加方法/功能,例如
Is it possible to add a method/function in this way, like
$arr = array(
"nid"=> 20,
"title" => "Something",
"value" => "Something else",
"my_method" => function($arg){....}
);
或者也许是这样
$node = (object) $arr;
$node->my_method=function($arg){...};
如果可能的话,我该如何使用该功能/方法?
and if it's possible then how can I use that function/method?
推荐答案
您不能将方法动态添加到stdClass并以常规方式执行.但是,您可以做一些事情.
You cannot dynamically add a method to the stdClass and execute it in the normal fashion. However, there are a few things you can do.
在第一个示例中,您正在创建关闭.您可以通过发出以下命令来执行关闭操作:
In your first example, you're creating a closure. You can execute that closure by issuing the command:
$arr['my_method']('Argument')
您可以创建一个stdClass对象并将其闭包分配给其属性之一,但是由于语法冲突,您无法直接执行它.相反,您将必须执行以下操作:
You can create a stdClass object and assign a closure to one of its properties, but due to a syntax conflict, you cannot directly execute it. Instead, you would have to do something like:
$node = new stdClass();
$node->method = function($arg) { ... }
$func = $node->method;
$func('Argument');
尝试
$node->method('Argument')
将生成错误,因为stdClass上不存在任何方法方法".
would generate an error, because no method "method" exists on a stdClass.
这篇关于在php中的std对象中添加方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!