开发者

How to avoid PHP to auto-create attributes?

When doing this :

开发者_StackOverflow社区
class MyClass
{
    public $myAttr;
}

$c = new MyClass();
$c->someStuff = 1;

I have no error message, no notice, no whatever to tell me "hey, I do not know someStuff !"

Is there anyway to make PHP less easy about this ?

Thanks


Implement the magic methods __get() and __set() and tell them to spit a notice. These methods are called when you access a property that wasn't declared (or isn't visible).

public function __get($name) {
    trigger_error(__CLASS__ . " object has no such property $name", E_USER_NOTICE);
    return NULL;
}

public function __set($name, $value) {
    trigger_error(__CLASS__ . " object has no such property $name", E_USER_NOTICE);
}


I often define a SafeObject to inherit from, which dies when I attempt to read/write an undefined attribute:

class SafeObject {
    function __get($key) { die("Attempt to get nonexistent member $key"); }
    function __set($key, $value) { die("Attempt to set nonexistent member $key"); }
}

The idea being I should never actually call either of these methods during production code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜