php中类错误中的数组引用


Array reference in a class error in 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();

似乎您的$u对象从未填充私有数组。

您可以创建一个新的对象$testA并填充它的数组。

这可能有助于您理解

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();
    }
}

another.php

require_once "testClass.php";
$u = new testArray();
print_r($u->PopulateArr());
print_r($u->printArr());

这里我们访问的是protected function PopulateArr的值而不是在函数中打印我只是将其替换为return并将其打印到另一个文件中在printArr函数中调用PopulateArr函数就是这样