Why declare PHP variable type in a comment?

前端 未结 5 2070
[愿得一人]
[愿得一人] 2021-02-02 09:51

I\'m fairly new to PHP, and I just started using NetBeans to develop my PHP code.

Out of the blue, as I entered a variable in a query, a dialog popped up and asked me to

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-02 10:41

    Despite netbeans use it for autocompletion it is often useful for documenting your code:

    In this case you know what this method gets and what it returns but inside the code you have no idea what is happening

    /**
     * Returns some stuff
     * @param string $someObj
     * @return array
     */
    public function someMethod($someObj) {
        $factoredObj = getObject($someObj); //you are not sure what type it returns
        $resultArray = $factoredObj->toArray();
        return $resultArray;
    }
    

    You can comment it with /* @var $variable type */ inside the code

    /**
     * Returns some stuff
     * @param string $someObj
     * @return array
     */
    public function someMethod($someObj) {
        /* @var $factoredObj someType */
        $factoredObj = getObject($someObj);
        $resultArray = $factoredObj->toArray();
        return $resultArray;
    }
    

    or

    $factoredObj = getObject($someObj); /* @var $factoredObj someType */
    

提交回复
热议问题