Im new to PHP Object Oriented Programming but I know to code in procedural way.
If this is my PHP Class
<?php
class person {
var $name;
function __construct($persons_name) {
$this->name = $persons_name;
}
function get_name() {
return $this->name;
}
}
?>
and if I access it in my PHP page
$jane = new person("Jane Doe");
echo "Her name is : ".$jane->get_name();
Question:
Is it really necessary to put the var $name; in my PHP class since
I can correctly get an output of Her name is : Jane Doe even without the var $name; in my PHP class?
Semantically, you should, as
$nameis indeed an attribute of your class. Your constructor already assigns$persons_nameto the attribute, but if you left thevar $name;out, the rest of your script wouldn’t really know that there’s such an attribute in your class. Additionally if your constructor didn’t assign it right away,person::get_name()would attempt to retrieve an undeclared$nameattribute and trigger a notice.As Brenton Alker says, declaring your class attributes explicitly allows you to set their visibility. For instance, since you have
get_name()as a getter for$name, you can set$nameasprivateso a person’s name can’t be changed from outside the class after you create apersonobject.Also, attempting to assign to undeclared class attributes causes them to be declared as
publicbefore being assigned.