PHP stdClass()和uu get()魔术方法
以以下代码为例:PHP stdClass()和uu get()魔术方法,php,object,singleton,stdclass,Php,Object,Singleton,Stdclass,以以下代码为例: class xpto { public function __get($key) { return $key; } } function xpto() { static $instance = null; if (is_null($instance) === true) { $instance = new xpto(); } return $instance; } echo
class xpto
{
public function __get($key)
{
return $key;
}
}
function xpto()
{
static $instance = null;
if (is_null($instance) === true)
{
$instance = new xpto();
}
return $instance;
}
echo xpto()->haha; // returns "haha"
现在,我正在尝试归档相同的结果,但不必编写xpto类。我想我应该写这样的东西:
function xpto()
{
static $instance = null;
if (is_null($instance) === true)
{
$instance = new stdClass();
}
return $instance;
}
echo xpto()->haha; // doesn't work - obviously
现在,是否可以向stdClass对象添加_get()神奇功能?我想不会,但我不确定。不,不可能。无法向stdClass添加任何内容。此外,与Java不同,Java中的每个对象都是对象的直接或间接子类,PHP中的情况并非如此
class A {};
$a = new A();
var_dump($a instanceof stdClass); // will return false
你到底想达到什么目的?你的问题听起来有点像“我想关上车门,但没有车”:-。OP看起来像是在尝试使用全局范围内的函数实现单例模式,这可能不是正确的方法,但无论如何,对于Cassy的回答,“你不能向stdClass添加任何内容”-这不是真的 只需为stdClass指定一个值,即可将属性添加到stdClass:
$obj = new stdClass();
$obj->myProp = 'Hello Property'; // Adds the public property 'myProp'
echo $obj->myProp;
但是,我认为您需要PHP5.3+来添加方法(匿名函数/闭包),在这种情况下,您可以执行以下操作。但是,我没有尝试过这个。但是,如果这确实有效,您能用magic\uu get()方法做同样的事情吗
更新:如评论中所述,您不能以这种方式动态添加方法。分配一个(PHP5.3+)就可以做到这一点,只需将一个函数(严格地说是a)分配给一个公共属性
$obj = new stdClass();
$obj->myMethod = function($name) {echo 'Hello '.$name;};
// Fatal error: Call to undefined method stdClass::myMethod()
//$obj->myMethod('World');
$m = $obj->myMethod;
$m('World'); // Output: Hello World
call_user_func($obj->myMethod,'Foo'); // Output: Hello Foo
谢谢Cassy,我想可能有一种模糊的方法来创建一些lambda类,但我想不是。感谢您的投入。=)这与所描述的不一样,不,您不能对
\uu get
执行相同的操作。它不是你附加的方法,它是一个函数。我确认这是可行的,但如前所述,该方法是一种属性,因此必须使用。