I am setting a class variable inside a class. Now, I have written a method that uses the variable. The code that I have written is like so
class someController extends someBase{
private $var;
var_dump($var); //line 3
public function someFunc(){
$this->var = null
$this->var = $this->otherFunction(); //assume this returns string "Barack Obama"
}
}
The first time the controller is accessed, the value on line 3 will be null
. How do I code it such that the next time I access this controller, the var_dump output on line 3 is "Barack Obama".
I have looked into getters and setter but since I am new to php, I am not able to wrap my head around how it works.
<?php
class someBase{
}
class someController extends someBase{
private $var = null;
private $count = 0;
//var_dump($var); you can't print anything directly from class itself, you must print it inside function.
public function someFunc(){
$this->count++;
if($this->count == 1)
var_dump($this->var); // null value can't be printed by echo or print as there is no value assigned to null value. in order to print null value you should print it as string
else
echo $this->var = $this->setter_function();
}
private function setter_function(){
return "Barack Obama";
}
}
$obj = new someController();
$obj->someFunc();
$obj->someFunc();
?>