I did an exercise in codeacademy related to objects in PHP. It asked me to define a public variable $name
in class Cat
:
<?php
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 . "<br>";
}
}
$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.