Re: [PHP5]__get, __set and isset()

From: Date: Tue, 31 Aug 2004 17:39:48 +0000
Subject: Re: [PHP5]__get, __set and isset()
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-195309@lists.php.net to get a copy of this message
Frédéric hardy wrote:
Is it possible to do something like this : class foo {
    private $array = array();
    function __construct()
    {
        ...
    }
    function __get($key)
    {
        return (isset($this->array[$key]) == false ? null : $this->array[$key]);
    }
    function __set($key, $value)
    {
        $this->array[$key] = $value;
    }
} $foo = new foo(); if (isset($foo->bar) == false)
    $foo->bar = 'bar';
else
    echo $foo->bar;
It seems that isset($foo->bar) return ALWAYS false. Bug ?
Not a bug, __get() and __set() are called only if !isset($foo->var). The purpose of __get and __set is to implement transparent getters and setters without forcing users to do function setVal($val) {
    $this->val = $val;
} function getVal() {
    return $this->val;
} If you are not sure which properties even exist, you probably shouldn't be using __get()/__set(), or should refactor so that you can rely upon certain values existing. If absolutely necessary, you can always provide function ifexists($name) {
    return isset($this->array[$name]);
} and then you can if ($o->ifexists('a')) instead of if (isset($o->a)) Greg

« previous php.general (#195309) next »