Add method in an std object in php

后端 未结 4 1449
说谎
说谎 2021-01-01 14:13

Is it possible to add a method/function in this way, like

$arr = array(
    \"nid\"=> 20,
    \"title\" => \"Something\",
    \"value\" => \"Somethi         


        
4条回答
  •  庸人自扰
    2021-01-01 14:48

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

提交回复
热议问题