I did an exercise in codeacademy related to objects in PHP. It asked me to define a public variable $name
in class Cat
:
class Cat {
public $isAlive = true;
public $numLegs = 4;
public $name;
public function __construct( $name ) {
$this->name = $name;
}
public function meow() {
return "Meow meow. " . $this->name . "
";
}
}
$cat1 = new Cat( "CodeCat" );
echo $cat1->meow();
?>
Is this public $name;
line actually needed? As I understand this, I call special function __construct
with an argument value CodeCat
. Then this CodeCat
is assigned to variable $this->name
and that's what I use later in function meow
. If I comment out the public $name;
line, then this does not affect the result.
Answer
Is this public $name; line actually needed? ... If I comment out the
public $name; line, then this does not affect the result.
PHP will create properties on your objects on request, even if you never formally declared them.
Class Thing{}
$a = new Thing();
$a->name = 'John';
echo $a->name; // John
echo $a->age; // doesn't break script but PHP gives 'Notice: undefined property'
So your code runs either way because PHP adds the name
property when you set it to something inside __construct()
. Since properties are public by default, you get the same result.
This code design (using properties without declaring them) is a poor habit for several reasons including:
- It's a nightmare for others who want to use or interact with your code
- It's a nightmare for you if you're dealing with anything more than a very simple script. In a large application it will be impossible to know does this instance of
Cat
have a name?, what about this instance?, what other properties does it have anyway? None of these will be easy to answer if you add properties dynamically across different functions, or worse, different files. - Calling code has no guarantee that a property exists, so your program will likely have many more bugs
- IDEs and code editors have no way to know the shape of your objects, so you're deprived of powerful tooling. Your scripts will take longer to write
No comments:
Post a Comment