Home > Article > Backend Development > PHP accesses non-existent properties without reporting an error?
Code:
<code><?php error_reporting(E_ALL | E_STRICT); class Father { private $name = 'meng'; } $father = new Father; $father->sex = 'male'; </code>
Then execute:
No questions asked. . .
Code:
<code><?php error_reporting(E_ALL | E_STRICT); class Father { private $name = 'meng'; } $father = new Father; $father->sex = 'male'; </code>
Then execute:
No problem. . .
PHP does not force attributes to be declared in the class. Writing it like this is actually equivalent to dynamically adding attributes to the object, but it is best not to write it like this, because maybe one object will be missed.
This is to dynamically add attributes to an object (instance of a class), and no error will be reported. However, if you access the attributes instead of adding attributes, an error will be reported. For example, if you are echo $father->sex
and It's not that $father->sex = 'male'
will report an error.