Why in the method greet()
must I not add a parameter $firstname
in the declaration of the function?
Wrong:
public function greet($firstname){
echo "Bonjour, mon nom est ". $this->firstname . "Ravi de vous rencontrer ! :-)";
}
Correct:
class Person {
public $isAlive = true;
public $firstname;
public function __construct($firstname,$lastname,$age){
$this->firstname = $firstname;
}
public function greet(){
echo "Bonjour, mon nom est ". $this->firstname . "Ravi de vous rencontrer ! :-)";
}
}
If you do not declare ,
public $firstname;
in the class, then it becomes a local variable,which cannot be accessed same as a class variable.
If you add this as an argument to the greet()
function, you are just returning the value that you pass to greet()
. The way you have it the value is set by the class constructor as a data member, and this is probably what you want as the information is related to the class instance and you want it to remain stored between calls to greet().
Hope this explains it!
It`s because you don't have to pass any $values to function if u don't need to. It all depends on your function declaration form.
Here u must pass the $param.
public function greet($param){
}
Here u can`t :
public function greet(){
}
Here u can, but u don't have to:
public function gree($param = null){
}
Any method that's declared inside the class have access to the properties that are in here with $this, like:
class newClass {
public $param;
public function sayName(){
return $this->param;
}
}