Drahcir
Drahcir

Reputation: 11972

__set not being called

I have the __set method below, it's not being fired. Note the echo '__set' at the top of the method.

public function __set($name, $value){
        echo '__set';
        if($this->{$name}==$value)  return;
        switch($name){
            case 'title':
            case 'body':
            case 'template':
            case 'date':
            case 'pageType':
                if(!$this->exists()){
                    $this->DB->insert('posts', array($name, $value));
                    $this->ID=($this->DB->autoIncrement('posts')-1)<1?1:($this->DB->autoIncrement('posts')-1);
                }
                else{
                    $this->DB->update('posts', array($name => $value));
                }
                $this->{"$name"}=$value;
                return;
            break;
        }
        $this->{$name}=$value;
    }

The method works fine when I call $class->__set(...); but not when I $class->title='whatever'. Hopefully just a small mistype or something but haven't spotted it in the last 15 mins.

Upvotes: 0

Views: 541

Answers (1)

user895378
user895378

Reputation:

If you're running into name collisions like those mentioned in the comments to your question, you could instead implement __get() with __set() to accomplish what you're trying to do like so:

class MyMagicClass
{
  protected $vals = array();

  public function __get($name)
  {
    if (isset($this->vals[$name])) {
      return $this->vals[$name];
    }
    throw new OutOfBoundsException("$name is not a valid property");
  }

  public function __set($name, $value)
  {
    $this->vals[$name] = $value;
    // do your other stuff here ...
  }
}

__get(), like __set(), is only called when the requested object property doesn't exist or isn't accessible (protected/private). If you do it like the above example, all your "magic" object properties will be stored in the protected $vals array and accessed through __get() and __set().

Upvotes: 4

Related Questions