Reputation: 1356
<?php
class ser {
public $a;
}
$x = new ser;
$x->b = 10;
var_dump($x);
Something like this.
Class ser
has only $a
property, but we can set $b
to new object of this class and it works despite this class doesn't have any $b
property
output
E:\XAMPP\htdocs\fun\test2.php:12:
object(kurde)[1]
public 'a' => null
public 'b' => int 10
Why this works?
Why we can add property and set it to this class while it doesn't belong exactly to this class?
How is that possible and why is that possible?
Any purpose? Sense of making this possible?
Upvotes: 1
Views: 1040
Reputation: 6319
This is what PHP refers to as "overloading". This is different to overloading in almost any other object oriented language.
If you do not like it, you can use the __set
magic method to throw an exception if a non-existent property is set:
public function __set($name, $value) {
throw new \Exception('Property "'.$name.'" does not exist')
}
You can tell from the comments on the documentation what the general consensus of this "feature" is.
Upvotes: 3