Avoid overloading attributes when using magic methods

1

I have the following PHP class:

<?php
class User{
    private $email = null;
    private $pass = null;

    public function __set($atrib, $value){
        $this->$atrib = $value;
    }

     public function __get($atrib){
        return $this->$atrib;
    }
}
?>

When I was testing I got the following error: INDIRECT MODIFICATION OF OVERLOADED PROPERTY HAS NO EFFECT I searched and saw that this error is directly connected to the magic methods so I searched for a solution to the problem, I removed the $ email and $ pass attributes from the class the problem was solved but this I wondered how I could determine the attributes of the class without generating the error: Inderect modification ... ?

Example usage:

$user = new User();
$user->email = $_GET['email'];
$user->pass = $_GET['pass'];
loginSearch($conn,$user);
function loginSearch($conn,$user){
        $query = "SELECT email, pass FROM usuarios WHERE email = :email AND pass = :pass";
        $stmt = $conn->prepare($query);
        $stmt->bindParam(':email',$user->email,PDO::PARAM_STR);
        $stmt->bindParam(':pass',$user->pass,PDO::PARAM_STR);
        return $stmt;
    }

The error occurs in the lines: $stmt->bindParam(':email',$user->email,PDO::PARAM_STR); and $stmt->bindParam(':pass',$user->pass,PDO::PARAM_STR);

Note: It ignores connection creation and execute of stmt.

Image of error generated:

    
asked by anonymous 07.02.2015 / 16:20

1 answer

1

When I had this problem, the solution was to declare __get with return by reference.

This can be done through the character & .

See:

<?php
class User{
    private $email = null;
    private $pass = null;

    public function __set($atrib, $value){
        $this->$atrib = $value;
    }

     public function &__get($atrib){
        return $this->$atrib;
    }
}
?>
    
10.02.2015 / 15:06