3

以下面的代码为例:

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

2 回答 2

4

不,这是不可能的。您不能向 stdClass 添加任何内容。此外,与 Java 不同,Java 中的每个对象都是 Object 的直接或间接子类,而 PHP 并非如此。

class A {};

$a = new A();

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

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

于 2009-12-13T09:37:05.723 回答
3

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

您可以通过为它们分配一个值来向 stdClass 添加属性:

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

但是,我认为您需要 PHP 5.3+ 才能添加方法(匿名函数/闭包),在这种情况下,您可以执行以下操作。但是,我没有尝试过这个。但如果这确实有效,你能用神奇的 __get() 方法做同样的事情吗?

更新:如评论中所述,您不能以这种方式动态添加方法。分配一个匿名函数(PHP 5.3+)就是这样做的,只是将一个函数(严格来说是一个闭包对象)分配给一个公共属性。

$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
于 2010-07-05T16:30:28.893 回答