Aug 3, 2012

Quick tip: magic methods and PhpStorm

If you use PhpStorm and add magic methods to a class (__get/__set/__call), you may notice that PhpStorm generates warnings for undefined class attributes and methods. A typical example is when you implement automatic getters and setters for protected instance variables:


class Foo {

    public function __get($name) {
        if ($name == 'bar') {
            return 'bar';
        }
        return NULL;
    }
}


You will get a warning on the second line if you write the code like this:

$foo = new Foo();
$bar = $foo->bar;

You can skip that warning by coding your class in the following way:

/**
 * @property $bar
 */
class Foo {

    public function __get($name) {
        if ($name == 'bar') {
            return 'bar';
        }
        return NULL;
    }
}


The same applies to methods processed by __call but there you need to use @method annotation with the method name:

/**
 * @method getBar
 */
class Foo {

    public function __call($name, $arguments) {
        if ($name == 'getBar') {
            return 'bar';
        }
        return NULL;
    }
}


Hope, this helps you to decrease amount of warnings in your code.

3 comments: