3

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?

Moppo
  • 18,797
  • 5
  • 65
  • 64
Siddharth Thevaril
  • 3,722
  • 3
  • 35
  • 71
  • Yes, this is a feature of PHP's objects. I think you should not rely on it. My opinion is it is for retrocompatibility with PHP4's object model (which looked like arrays with methods). I could not find any official documentation about this. – Mat Jul 19 '15 at 07:38
  • Here's a way to avoid it: http://stackoverflow.com/q/9136464/472495 – halfer Jul 19 '15 at 07:53
  • Possible duplicate http://stackoverflow.com/questions/25132970/undefined-public-member-variables-getting-initialized – Gogol Jul 19 '15 at 08:27

1 Answers1

5

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.

2hamed
  • 8,719
  • 13
  • 69
  • 112