Search code examples
autocompletephpstorm

Autocomplete for unknown properties


Is it possible to PhpStorm to autocomplete unknown properties? Here is sample code:

class Fields {
    public function __construct($data) {
        foreach ($data AS $d) {
            $propName=$d['id'];
            $this->$propName=$d['value'];
        }
    }
}

$data=[
    ['id'=>'myId', 'value'=>'Name'],
    ['id'=>'second', 'value'=>'Second]
];

$fields=new Fields($data);

$fields->second;//comes from autocpmplete

I want 'second' or 'myId' property to be autocompleted. Is it possible?


Solution

  • Is it possible to PhpStorm to autocomplete unknown properties?

    Yes and No -- it depends on how you plan to use it.


    If you want to have it absolute dynamic (e.g. the same Fields class but in one file $fields variable (instance of that Fields class) will have one set of fields and in another completely different) -- then answer is No.


    Otherwise it's possible to declare non-existing property via @property tag (see detailed link) in PHPDoc comment for that class.

    /**
     * @property string $abc Optional description here
     */
    class Fields {
    ...
    

    Now every instance of Fields will have abc property offered in completion.

    With that in mind you can have all actual code/logic in Fields class and then declare specific fields in child classes:

    /**
     * @property string $first
     */
    class FirstClassFields extends Fields {
    ...
    }
    
    /**
     * @property string $second
     */
    class SecondClassFields extends Fields {
    ...
    }