【问题标题】:PhpStorm: how to tell the var type of an array member?PhpStorm:如何判断数组成员的 var 类型?
【发布时间】:2017-02-08 09:45:36
【问题描述】:

我使用PhpStorm 2016.2.1 IDE。我有一个类型化数组(所有成员都属于相同的已知类),我希望 IDE 知道类型,以便它可以帮助我完成自动完成/智能感知。

class MyClass{    
     /**
     * @var array
     */
    public $userArray;

    public addUser($uid){ $this->$userArray[$uid] = new User($uid); }

    public processUser($uid){

        $oUser = $this->$userArray[$uid];
            //since the PHP array can contain anything, the IDE makes 
            //no assumption about what data type $oUser is. How to let it 
            //know that it's of type User?
    }
}

我试过了……

 /**
 * @var User
 */
public $oUser = ...;

还有

 /**
 * @type User
 */
public $oUser = ...;

到目前为止,我唯一要做的就是使用 getter 函数:

/**
* @return User
*/
function getUser($uid){ return $this->$userArray[$uid]; }

function processUser($uid){
    //now the IDE knows the type of $oUser
    $oUser = $this->getUser($uid);
}

但是为了获得更好的 IDE 支持而使用不需要的函数调用来减慢脚本似乎是个坏主意。

知道如何让 PhpStorm 知道变量的类型吗?甚至更好:如何告诉它数组将包含在该数组的 PHPDoc 元数据中的哪种类型?

【问题讨论】:

    标签: php ide phpstorm intellisense phpdoc


    【解决方案1】:

    对于类变量,如你所知,你可以简单地做

    @var User

    对于局部变量,它不是官方支持的格式,但您还必须指定变量名称:

    @var User $oUser

    特定于 PHPStorm,您需要使用双星号(我认为这是唯一需要它的 IDE,请考虑一下):

    /** @var User $oUser */

    查看PHPDoc manual了解更多信息

    【讨论】:

    • 谢谢;这适用于局部变量!有没有办法指示类型化数组? (告诉 IDE 所有数组成员都属于给定类)
    • 您可以使用@var User[] 来建议一组用户对象,但我不知道 PHPStorm 是否支持它(可能!)phpdoc.org/docs/latest/guides/types.html#arrays
    • 另一种选择是在 foreach 循环中提供提示,虽然有点混乱
    • @var User[] 也工作了 :-) IDE 说 $oUser 如果类型为 User|mixed
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2012-03-16
    • 2010-10-24
    • 1970-01-01
    • 2012-06-16
    • 2022-01-22
    • 2021-08-19
    相关资源
    最近更新 更多