简体   繁体   中英

Unexpected behaviour of constructor in php

I am new to php and was learning the oop concepts of it.
Along the process i saw this which i couldn't explain.
How can the constructor access a property which is not even a part of the class ?

  <?php
    class Person {
      public $isAlive = true;

      function __construct($name) {
          $this->name = $name;
      }

      public function dance() {
        return $this->name;
      }

    }

    $me = new Person("Shane");
    if (is_a($me, "Person")) {
      echo "I'm a person, ";
    }
    if (property_exists($me, "name")) {
      echo "I have a name, ";
    }
    if (method_exists($me, "dance")) {
      echo "and I know how to dance!";
    }

  ?>

The output of above is
How is it so if 'name' is not declared as a property of Person class ?

Unlike Java, you can set variables on the fly without declaring them first.

So $this->name will basically put a public $name variable as a class variable.

PHP class variables can be created at any time, so it is different than other OO languages such as Java and C#. It's always a good idea to declare the variable in the class declaration, however, so it is easier for the programmer to find and understand later. eg $name = NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM