是否可以在stdClass下定义函数


Is it possible to define functions under stdClass

这里我试图在stdClass对象下定义一个函数。

<?php
$x= function($name){return "Hello ".$name;};
echo $x("Sun");
$hey = (object)[ "x" => function($name){return "Hello ".$name;}, "y" =>"Hello Venus"];
echo $hey->x("Mercury");
echo $hey->y;

但它说:致命错误:调用未定义的方法stdClass::x()

这是最接近的:

$x = function ($name) { return 'hello ' . $name; };
$obj = new stdClass();
$obj->x = $x;
echo call_user_func($obj->x, 'john'); // this will work
echo $obj->x('john');                 // this will not work

不过,您不需要在php7中使用call_user_func。