【问题标题】:Accessing PHP class stored as in array访问以数组形式存储的 PHP 类
【发布时间】:2014-08-24 11:47:31
【问题描述】:

我希望我在这里遗漏了一些简单的东西。我有一个创建另一个类的数组的类。当我访问数组的元素时,我的 IDE(老实说,我还没有在运行时尝试过,因为我还没有完成编码)不能将元素识别为来自原始类。所以要么我必须习惯它,因为这就是 PHP 的工作方式,要么我需要知道处理它的正确方法。这可能是一个 PHP IDE (PHPStorm) 问题,但感觉有些不对劲。

例如假设我定义了一个类:

class memberClubAssoc  {

    private $_id;

    function __construct() {
        // do stuff
    }

    // other various functions
}

...然后我有另一堂课。有问题的函数是 dealWithArray(),我在其中循环遍历类数组并访问类实例,然后尝试将它们用作类实例。

class member {
    private $_id;

    private $_aClubAssociations;

    function __construct() {
        // do stuff

        $this->_aClubAssociations = array();
    }

    // fill in the array with instances of the memberClubAssoc class
    function someFunction() {
        $this->_aClubAssociations[0] = new memberClubAssoc(1);
        $this->_aClubAssociations[1] = new memberClubAssoc(2);
        // ...
    }

    // here's the function in question
    function dealingWithArray() {
        foreach ($this->_aClubAssociations as $clubAssoc) {
            // how does PHP know that $clubAssoc is actually an instance of 
            // memberClubAssoc? - PHPStorm certainly does not because when
            // I try to access a method on the class PHPStorm says it 
            // doesn't exist.
        }
    }
}

【问题讨论】:

    标签: php arrays function class


    【解决方案1】:

    使用类似的引用

    function dealingWithArray() {
        foreach ($this->_aClubAssociations as $clubAssoc) {
            /** @var $clubAssoc memberClubAssoc **/
        }
    }
    

    现在phpstorm知道$clubAssoc中的数据是来自memberClubAssoc类型的一个类。如果您处理数组值,则不会出错,您需要告诉 PHPStorm 返回什么类型的数据,因为 PHPStorm 无法自行获取此信息。

    【讨论】:

    • 太棒了!谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2020-12-29
    • 2020-09-27
    相关资源
    最近更新 更多