Loading

Variable types

As an occasional PHP user, the simple and obvious tricks often pass me by. So, I rely a lot on the intelli-sense you get from PHPStorm from JetBrains. It helps me achieve what I need to achieve even though I rarely use PHP in anger.

Where I fall short most often is objects with properties and methods. I define a variable which I later assign a class instance to and then sit there struggling to remember what methods the class has. Intellisense can't help because it just has a variable:

    private $articles = array();

I know this is an array of article instances, but how is PHPStorm supposed to know. And, if PHPStorm doesn't know how is it supposed to help me.

Turns out, you can annotate variables to let PHPStorm know what it is going to be:

    /* @var article[] $articles */
    private $articles = array();

The @var directive tells PHP what the data type will be, an array of article objects and matches it with the $articles variable. From now, I get intelligence from the $articles variable.

A variant of this can be particularly useful for return types from methods.

    /**
     * Returns a list of subcategories within the category
     *
     * @return subCategory[]
     */
    public function getSubcategories($category ) {
        foreach ($this->getCategories() as $cat) {
            if ($cat->getCategoryName() == $category) {
                return $cat->getSubCategories();
            }
        }

        return null;
    }

Here I have a method that returns an array of subCategory objects. Because we are returning an array from a method, it makes sense to use the other tool in our arsenal, the @return directive. Like our @var this tells PHPStorm what the return type is and allows PHPStorm to generate its intellisense helpers for us.