Reputation: 3798
Coming from a Java background, I find this odd. Please have a look at this code -
<?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>";
?>
OUTPUT :
People Object
(
[name:People:private] => Sam
[age:People:private] => 22
[ID] => 12057
)
Having not created any property as ID
in the People
class, yet I can assign a value to ID
outside the class using p1
.
In Java, this would give an error -
cannot find symbol
Is this a feature in PHP? If it is then what is it called? And how is it beneficial?
Upvotes: 3
Views: 187
Reputation: 9067
Since PHP is a dynamically typed scripting language it allows for Dynamic Properties
. I refer you to this 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.
Upvotes: 5