2009年6月10日星期三

Re: [fw-mvc] get and set accessors

Hi =)

I finally had a chance to use Matthew's code and discovered that it
results in an infinite loop if I do this:

$obj = new Foo();
$obj->setName('testing');

According to the PHP manual, "__set() is run when writing data to
inaccessible members."
http://us2.php.net/manual/en/language.oop5.overloading.php

It seems like the variable isn't recognized as an accessible member of
the object, so PHP keeps calling __set (Name, _Name, __Name, etc.).

I modified the __set method like this:

public function __set($name, $value) {
$method = 'set'.$name;
if (method_exists($this, $method)) {
return $this->$method($value);
}
parent::__set($name, $value);
return TRUE;
}

Now it's not an infinite loop, but the set method is still called
twice. Any ideas on how to solve this?

Thanks,

Ed


>    class Foo
>    {
>        public function __set($name, $value)
>        {
>            $method = 'set' . $name;
>            if (method_exists($this, $method)) {
>                $this->$method($value);
>                return;
>            }
>
>            $prop = '_' . $name;
>            $this->$prop = $value;
>        }
>
>        public function __get($name)
>        {
>            $method = 'get' . $name;
>            if (method_exists($this, $method)) {
>                return $this->$method();
>            }
>
>            $prop = '_' . $name;
>            if (!property_exists($this, $prop)) {
>                return null;
>            }
>            return $this->$prop;
>        }
>
>        public function __call($method, $args)
>        {
>            if ('set' == substr($method, 0, 3)) {
>                $name  = substr($method, 3);
>                $value = array_shift($args);
>                $this->__set($name, $value);
>                return;
>            }
>            if ('get' == substr($method, 0, 3)) {
>                $name  = substr($method, 3);
>                return $this->__get($name);
>            }
>            throw new BadMethodCallException();
>        }
>    }

没有评论: