Search code examples
phpyiiphpstormphpdoc

How to document static class properties in PHP


Given the following scenario, where you have a static property on Foo documented as an instance of FooApp, an extended class Bar, and at runtime it turns out that the static property is actually set to an instance of BarApp rather than FooApp:

class Foo
{
    /** 
     * @var FooApp
     */
    public static $app;
}

class Bar extends Foo
{
}

Bar::$app = BarApp();

…what is the proper way to document Bar so that it’s clear that its static $app is going to be set to a BarApp instance rather than FooApp?

I’ve tried the following but PhpStorm doesn’t respect it, probably because @property isn’t meant for static properties:

/**
 * @property BarApp $app
 */
class Bar extends Foo
{
}

So far the only thing I’ve come up with is actually overriding $bar in the code:

class Bar
{
    /** 
     * @var BarApp
     */
    public static $app;
}

This is a bit annoying since it results in extra code when theoretically extra documentation would have sufficed (as in the case of overriding instance-level properties and methods’ documentation using @property and @method).

(The use case here is a Yii application - Foo represents BaseYii and Bar represents a custom class that extends it; FooApp represents yii\base\Application and BarApp represents a custom class that extends it.)


Solution

  • Please note: This is a tracking answer to help people arriving here from search results.

    At the time of writing, there simply is no (official) documentation tag to annotate "magic" static properties, neither in the PHPDocumentor standard nor the proposed PSR19.

    If you're part of the PHP-FIG (looking at you @Chuck Burgess), you might want to consider adding this to PSR19, preferably as an extension of the @property tag — for example like so:

     * @property static type $name Free text description
    

    With "static" being an optional keyword that may be omitted for non-static, virtual properties.

    Otherwise, I've opened an issue on the PHPStorm issue tracker. If you'd like this being implemented in PHPStorm, consider voting for it.