Add method in an std object in php

爷,独闯天下 提交于 2019-11-30 17:35:21
keelerm

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')

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');

Attempting

$node->method('Argument')

would generate an error, because no method "method" exists on a stdClass.

See this SO answer for some slick hackery using the magic method __call.

This is now possible to achieve in PHP 7.1 with anonymous classes

$node = new class {
    public $property;

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

// and access them,
$node->property;
$node->myMethod('arg');

Since PHP 7 it is also possible to directly invoke an anonymous function property:

$obj = new stdClass;
$obj->printMessage = function($message) { echo $message . "\n"; };
echo ($obj->printMessage)('Hello World'); // Hello World

Here the expression $obj->printMessage results in the anonymous function which is then directly executed with the argument 'Hello World'. It is however necessary to put the function expression in paranetheses before invoking it so the following will still fail:

echo $obj->printMessage('Hello World'); 
// Fatal error: Uncaught Error: Call to undefined method stdClass::printMessage()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!