即使我没有 this 变量,当我访问它时,我也没有收到错误

Even though I don't have a this variable, when I am accessing it, I am not getting an error

<?php
class Test{
    public $test_1, $test_2;
}


$object = new Test();
$object->test_1 = "THIS IS A TEST";
$object->test_2 = "THIS IS A TEST 2";
$object->test_3 = "THIS IS A TEST 3";

var_dump($object);

如您所见,我没有名为 test_3 的变量。但我没有收到错误。它工作得很好。为什么?这是我得到的输出。

object(Test)#1 (3) {
  ["test_1"]=>
  string(14) "THIS IS A TEST"
  ["test_2"]=>
  string(16) "THIS IS A TEST 2"
  ["test_3"]=>
  string(16) "THIS IS A TEST 3"
}

在 PHP 中,您可以即时创建 public 成员变量。如果你想防止这种情况,你可以重载 __set() magic method 并在有人试图这样做时抛出异常:

class Test{
    public $test_1, $test_2;

    public function __set($name, $value) {
        throw new \Exception('You cannot do this!');
    }
}