开发者

How to get type hinting / autocompletion for Objects that came out of an array?

In my framework, I have a method that returns an array with objects. It looks pretty much like this:

开发者_运维知识库
    /**
     * @return array Array with Action objects
     */
    public function getActions() {
        return $this->actions;
    }

The user of this Class will get an doc-popup when calling this method, which only says that this method will return an array. But that's it! Next, when the user gets an object out of the array, the IDE is plain stupid and doesn't know / suggest / autocomplete anything.

Is there anything I can do as a framework developer to make life of the framework users easier here? Or what else can I suggest them to do, so their IDE knows what kind of object is returned from the array?

Or in general: How to let the IDE know what kind of object came from the array, so that it can suggest what methods are available for that object?


When you call getActions() method you can prepend comment line before iterated array of objects:

$actions = $o->getActions();

/* @var Action $action */
foreach ( $actions as $action ) {
    ...
}


I think you can't hint on the type of an array member other than maybe assigning it explicitly like so:

$my_object = new myClass();
$my_array[567] = $my_object;

the only idea that comes to mind is to use an object for this->actions instead of an array. That object you could predefine for any decent IDE to understand.


php is a dynamically/weakly typed language, objects in arrays could be anything. so IDEs cannot know what object to expect. imagine the following array:

array ( 1, "string", someObject, array (1,"string",3) );


JetBrains new WebIDE has the best static code analysis, you can just use @return ElementType[] there. And it can infere types directly from the actual code too - see details on their site


As @Alexey Gopachenko said, some new IDEs (and also phpdoc documentation) support the sintax @return ElementType[]

/**
 * @return MyObj[]
 */
function getObjects() { return [new MyObj(), new MyObj()]; }

For your example:

/**
 * @return Action[]
 */
public function getActions() {
    return $this->actions;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜