php中类错误中的数组引用

php中类错误中的数组引用,php,arrays,class,object,Php,Arrays,Class,Object,我有一个类,它填充并打印一个数组 <?php class testArray { private $myArr; public function __construct() { $myArr = array(); } public static function PopulateArr() { $testA = new testArray(); $testA->populateProtectedA

我有一个类,它填充并打印一个数组

<?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
对象似乎从未填充私有数组


相反,您创建了一个新对象
$testA
并填充其数组。

您刚刚错过了一件事,您必须分配
$u->PopulateArr()的结果添加到
$u
,否则将无法获取通过该方法调用创建的对象,因此:

$u = new testArray();
$u = $u->PopulateArr(); // this will work
$u->printArr();
也可以这样做:

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

这可能有助于你理解这条路

class testArray
{
    private $myArr;

    public function __construct() { 
        $this->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';
        return $this->myArr;
    }
    public function printArr() {
        echo "<br> 2nd Array";
        return $this->PopulateArr();
    }
}

这里我们访问的是
受保护函数PopulateArr
的值,而不是在函数中打印,我只是将其替换为
return
,并在另一个文件上打印,而在
printArr
函数中只需调用
PopulateArr
函数即可
需要返回
$this->myArr
公共函数uuu构造(){$myArr=array();}应该变成:公共函数uu构造(){$this->myArr=array(),但你称它为一个实例method@MarkBaker在这两种情况下都是错误的,不需要返回任何内容,而且静态方法也可以从对象中调用too@GeorgeGarchagudashvili-然后,您可能会解释海报试图做什么,并解释为什么
PopulateArr()
被定义为静态的?事实上,在你提醒我说我错了之前,我已经放弃了试图弄明白这其中的逻辑
require_once "testClass.php";
$u = new testArray();
print_r($u->PopulateArr());
print_r($u->printArr());