微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php中类错误中的数组引用

我有这个类填充和打印一个数组

<?PHP

class testArray
{
    private $myArr;

    public function __construct() { 
        $myArr = array();
    }
    public static function PopulateArr() {

        $testA = new testArray();
        $testA->populateProtectedArr();
        return $testA;

    }
    protected function populateProtectedArr()
    {
        $this->myArr[0] = 'red'; 
        $this->myArr[1] = 'green'; 
        $this->myArr[2] = 'yellow';
        print_r ($this->myArr); 


    }
    public function printArr() {
        echo "<br> 2nd Array";
        print_r ($this->myArr);
    }
}
?>

我从另一个文件中实例化该类,并尝试在不同的函数中打印该数组.

<?PHP
    require_once "testClass.PHP";


    $u = new testArray();
    $u->PopulateArr();
    $u->printArr();
?>

我无法在printArr()函数中打印数组.我想引用我设置值的数组.

解决方法

你错过了一件事,你必须分配$u-> PopulateArr()的结果;再次使用$u,否则您将无法从该方法调用获取您创建的对象,因此:

$u = new testArray();
$u = $u->PopulateArr(); // this will work
$u->printArr();

这也可以这样做:

$u = testArray::PopulateArr();
$u->printArr();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐