为什么 PHP 允许从 class 外部创建 class 属性?

why does PHP allow creating class properties from outside the class?

来自 Java 背景,我觉得这很奇怪。请看一下这段代码 -

<?php  
    class People {
        private $name;
        private $age;
        public function set_info($name, $age) {
            $this->name = $name;
            $this->age = $age;
        }

        public function get_info() {
            echo "Name : {$this->name}<br />";
            echo "Age : {$this->age}<br />";
        }
    }

    $p1 = new People();
    $p1->set_info("Sam",22);
    $p1->get_info();

    $p1->ID = 12057;

    echo "<pre>".print_r($p1,true)."</pre>";
?>

输出:

People Object
(
    [name:People:private] => Sam
    [age:People:private] => 22
    [ID] => 12057
) 

没有在 People class 中创建任何 属性 作为 ID,但我可以在 [=35] 之外为 ID 赋值=] 使用 p1.

在 Java 中,这会产生错误 -

cannot find symbol

这是 PHP 中的功能吗?如果是那么它叫什么?它有什么好处?

由于 PHP 是一种动态类型的脚本语言,因此它允许 Dynamic Properties。我建议你参考这个 this article.

Languages like JavaScript and Python allow object instances to have dynamic properties. As it turns out, PHP does too. Looking at the official PHP documentation on objects and classes you might be lead to believe dynamic instance properties require custom __get and __set magic methods. They don't.