Question

I have this class:

class activeUser {

    private $data = array();

    private $textStatus = array(
        "s" => "admin",
        "a" => "user",
        "p" => "notYetAccepted",
        "b" => "banned",
        "g" => "guest"
    );

    function __construct($id) {
        $data = db::singleton()->query("SELECT * FROM usuarios WHERE id=$id")->fetch();
        var_dump($data);
        $this->data["status"] = $this->textStatus[$this->data["status"]];
    }

    public function __get($name)
    {
        if (array_key_exists($name, $this->data))
            return $this->data[$name];
        else
            return null;
    }    
}

And I call it here:

require "activeUser.php";
require "db.php";

$id = 4;
$data = db::singleton()->query("SELECT * FROM usuarios WHERE id=$id")->fetch();

$exampleUser = new activeUser(4);
echo $exampleUser->nick;

The var_dump returns me the expected array with the indexes: "id, email, password, nick, status, etc.". But just at the next line I got: "Notice: Undefined index: status".

Why? It's the first time I use php magic methods, but I don't found any sense at the result.

Was it helpful?

Solution

You are setting the local variable $data in the constructor, but referencing the member $this->data later. Pick one or the other. I assume you mean to set the member, notice line 2:

function __construct($id) {
    $this->data = db::singleton()->query("SELECT * FROM usuarios WHERE id=$id")->fetch();
    var_dump($this->data);
    $this->data["status"] = $this->textStatus[$this->data["status"]];
}

It also looks like you are accessing db within the constructor, although this may not be in scope. Please elaborate on the contents of the db.php file to get an answer to this potential problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top