0

我正在尝试使用该类的本地函数将一些数据附加到该类中声明的数组中,但是在附加之后,来自外部的转储报告了一个空数组:

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);
?>

我究竟做错了什么?

4

1 回答 1

1

您将值分配给global $arr而不是对象的$arr.

function appendData() {
    global $arr;

    $arr[] = "d";
}

应该

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

您可以在 PHP 的有关Classes 和 Objects的文档中找到类似的信息。

于 2013-06-18T16:23:12.863 回答