2

可能重复:
PHP 中静态属性的 Magic __get getter

是否可以像这样捕获对静态参数的调用:

class foo
{
    public static $foo = 1;
    //public static $bar = 2; 

    public function catch_bar_call()
    {
        print "Calling an undefined property";
    }
}


print foo::$foo //1
print foo::$bar //error

而不是得到一个错误,我想要一个方法被调用。我知道它可能通过 __get() 魔术方法,但你必须为此实例化你的类,这在静态参数上是不可能的。

4

1 回答 1

0

来自 PHP 文档

$name 参数是与之交互的属性的名称。__set ()方法的 $value 参数指定 $name'ed 属性应设置的值。

属性重载仅适用于对象上下文。这些魔术方法不会在静态上下文中触发。因此这些方法不应该被声明为静态的。从 PHP 5.3.0 开始,如果其中一个魔术重载方法被声明为静态,则会发出警告。

我认为你能做的是

class Test {
    private static $foo = 1;
    // public static $bar = 2;
    public static function foo() {
        return self::$foo;
    }

    public static  function __callStatic($n,$arg) {
         print "\nCalling an undefined property $n";
    }
}
echo "<pre>";
print Test::foo(); // 1
print Test::bar(); // Calling an undefined property bar

输出

1
Calling an undefined property bar
于 2013-01-07T15:30:57.400 回答