Search code examples
phpmagic-methods

Why is __get called instead of __call when I call a nonexistent method?


I have a class that looks like this:

class MyClass
{
    public __get($prop)
    {
        $method = 'get' . ucfirst($prop);
        if (method_exists($this, $metodo))
            return $this->$metodo();
        if (property_exists($this, $prop))
            return $this->$prop;

        throw new Exception("Nonexisting property $prop");
    }

    public function __call($method, $args)
    {
        $prop = strtr($method, 'add', '');
        $prop = lcfirst($prop);

        if (is_array($this->$prop))
            array_push($this->$prop, $args[0]);
    }
}

But if I do $obj->addTags('test'); it calls the __get, witch gives me an Exception with the message: "Nonexisting property addTags"

What should I do to my __call be invoked instead of my __get?

Thanks in advance!


Solution

  • I just replaced strtr for str_replace. I wasn't getting the right property name, so now it works.

    I'll mark it as answered as soon as it's allowed by Stack Overflow.

    :-D