2009-12-13 64 views
1

以下面的代码为例:PHP stdClass的()与__get()魔术方法

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 

现在,是有可能__get()魔法功能添加到stdClass的对象?我猜不是,但我不确定。

回答

4

不,这是不可能的。你不能向stdClass添加任何东西。另外,与Java不同的是,每个对象都是Object的直接或间接子类,但在PHP中并非如此。

class A {}; 

$a = new A(); 

var_dump($a instanceof stdClass); // will return false 

你真的想达到什么目的?你的问题听起来有点像“我想关上我的车的门,但没有一辆车”:-)。

+0

感谢卡西,我认为可能有一种晦涩的方式来创建某种类的lambda类,但我猜不是。谢谢您的意见。 =) –

3

该OP看起来像他们试图使用全局范围内的函数来实现单例模式,这可能不是正确的方法,但无论如何,关于Cassy的回答,“你不能添加任何东西到stdClass” - 这是不正确的。

您可以通过一个简单的值将它们添加属性的stdClass的:

$obj = new stdClass(); 
$obj->myProp = 'Hello Property'; // Adds the public property 'myProp' 
echo $obj->myProp; 

不过,我认为你需要PHP 5.3+,以添加方法(匿名函数/闭包),其中你可能会做下面的事情。但是,我没有试过这个。但是,如果这确实起作用,你可以用magic __get()方法做同样的事情吗?

更新:正如注释中所述,您不能以这种方式动态添加方法。指定anonymous function(PHP 5.3+)就是这样做的,只需将函数(严格为closure object)分配给公共属性即可。

$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 
+1

这不起作用。您不能将方法添加到stdClass。 –

+2

这不符合描述,不,你不能用'__get'做同样的事情。这不是你附加的方法,而是一种功能。 http://codepad.viper-7.com/nn4h0J – Ryan

+1

我确认这是行不通的,但正如注意到的那样,这个方法是一个属性,必须这样使用。 – ezraspectre

相关问题