0
I am trying to recover the value of a private property of my class using the magic __get method. According to the PHP documentation, every time I try to access a private or protected property of a class, it will fire __get. However, he is not being executed.
class Test{
private $conexao;
private static $connectionInstance;
public function __get($valor){
echo '13';
if($valor === "conexao"){
if(!isset($this->conexao)){
$this->conexao = new stdClass;
}
return $this->conexao;
}else if($valor === "conexaoo"){
if(!isset($this->conexao)){
$this->conexao = new stdClass;
}
return $this->conexao;
}else{
return null;
}
}
public static function getInstance(){
if(self::$connectionInstance === null){
self::$connectionInstance = new Test;
}
return self::$connectionInstance;
}
public static function problem(){
$instance = self::getInstance();
return $instance->conexao;
}
}
$test = new Test;
var_dump($test::problem());
In the code above, whenever I try to access connection from within the method problem, it does not fire the __get method, however, if I replace connection for related, which is an undeclared property, it triggers the method.
Can someone explain to me why?
He only fires the method
__get
when the people accessing it don’t have access to the field. As you are accessing the field from within the class itself, you will have access to the private field and thus there is no reason to call the magic method.– Woss
In that case, he will ignore the fact that they are different instances?
– João Paulo M. Bandolin
Yes, because no matter what the instance is, it is accessing the field within the class itself.
– Woss