php中类错误中的数组引用

时间:2015-07-07 07:10:20

标签: php arrays class object

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

<?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()函数中打印数组。我想引用我设置值的数组。

3 个答案:

答案 0 :(得分:1)

您的$u对象似乎永远不会填充私有数组。

而是创建一个新对象$testA并填充其数组。

答案 1 :(得分:1)

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

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

这也可以这样做:

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

答案 2 :(得分:1)

这可能有助于您了解

的方式
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函数内调用{{1}功能就是这样