PHP:将数据追加到类中的数组将导致从类外部转储一个空数组


PHP: appending data to an array inside a class results in an empty array dump from outside the class

我试图通过使用类的局部函数将一些数据附加到类内声明的数组中,但是从外部转储,在附加之后,正在报告一个空数组:

Checking...
array(0) { }

代码如下:

error_reporting(E_ALL);
ini_set('display_errors', '1');
class workerClass {
    // With the following declaration, the dump outside the class will report only "a", "b" and "c".
    //public $arr = array("a", "b", "c");
    // With the following declaration instead, the dump outside the class will report an empty array.
    public $arr = array();
    function appendData() {
        global $arr;
        $arr[] = "d";
    }
}
// Start check.
echo "Checking...<br />";
$worker = new workerClass();
// Trying to append some data to the array inside the class.
$worker -> appendData();
var_dump($worker -> arr);
?>

我做错了什么?

您正在将值赋给global $arr而不是对象的$arr

function appendData() {
    global $arr;
    $arr[] = "d";
}
应该

function appendData() {
    $this->arr[] = "d";
}

你可以在PHP的文档中找到类似的关于类和对象的信息