Problem with the magic method __get

Asked

Viewed 29 times

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?

  • 1

    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.

  • In that case, he will ignore the fact that they are different instances?

  • 1

    Yes, because no matter what the instance is, it is accessing the field within the class itself.

1 answer

0


Thanks to the help in the comments I managed to get the answer.

The problem is that, regardless of the instance, since it is the same class, the __get method will never be triggered, because the class itself has access to its private properties, thus not depending on the magic method.

I thank Woss for his explanation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.