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.
题
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 I'm a person, I have a name, and I know how to dance!
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.
e.g. $name = NULL;