(on Wednesday, 10 June 2009, 02:05 PM -0700):
> 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?
Make sure you're at the minimum defining the properties you'll be
setting within your class:
class Foobar extends Foo
{
protected $_bar;
}
This will ensure that it doesn't attempt to hit __set() from within your
setter, as the property has been declared (even though it has no value).
> > 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();
> > }
> > }
>
--
Matthew Weier O'Phinney
Project Lead | matthew@zend.com
Zend Framework | http://framework.zend.com/
没有评论:
发表评论