Why does PHP allow you to create class properties outside of the class?

Coming from a Java background, I find this strange. 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
) 

      

Without creating any property like ID

in a class People

, but I can assign a value ID

outside of the class with p1

.

In Java this will result in an error -

cannot find symbol

Is this a PHP function? If this is what is called? And how is it beneficial?

+3


source to share


1 answer


Since PHP is a dynamically typed scripting language, it allows Dynamic Properties

. I am linking to this article .



Languages ​​such as JavaScript and Python allow object instances to have dynamic properties. As it turns out, PHP does too. Looking at the official PHP documentation for the objects and classes you can cast you believe that dynamic instance properties require custom __get and __set magic methods. They don't.

+5


source







All Articles