I’m trying to create a global context variable in one of my libraries, but can’t seem to figure out how to make the variable stick. Below is a sample of my code:
class test{
function tester(){
echo context::getContext();
echo '<br />';
context::setContext(2);
echo context::getContext();
echo '<br />';
new test2();
}
}
class test2{
public function __construct(){
echo context::getContext();
}
}
class context{
protected static $contextNum = 0;
public function getContext(){
return isset($this->contextNum) ? $this->contextNum : 0;
}
public function setContext($num){
$this->contextNum = $num;
}
}
This ends up echoing:
0
2
0
How can I make it so that it echoes out?
0
2
2
Change
to
Use static modifiers for methods
setContext()andgetContext()Also I would advise you to add
throw new Exception('Can\'t create instance of this class')to__construct()method ofcontext.