PHP-Object-Oriented :即使属性未在对象定义中声明,也会被分配


PHP-Object-Oriented: The property is assigned even though it is not declared in the object definition

<?php
class Store
{
}
$obj1 = new Store() ;
$obj1 -> storeName = 'Book Store' ;
echo $obj1 -> storeName ;
?>

当我执行这个php脚本时,它给出的输出是Book Store

不应该触发一个错误,说属性未定义吗?

究竟发生了什么,为什么?

您可以随时随地将新属性附加到对象。对象不是"写保护"或类似的东西。此类附加属性具有 public 的可见性。

一个微不足道的例子是stdClass;在这样的对象上设置值只能通过这个机制,否则stdClass是完全无用的:

$foo = new stdClass;
$foo->bar = 'baz';