Question

I have a business logic class, which holds all the data of an user. The class should be able to insert/fetch/update/delete the user from a mysql database.

I started creating all the properties like username,password,email, etc... but the I realized that having a single dictionary containing all the properties is more convenient, because I frequently need to concert the user object to a dictionary or a string, and I need to hold key-value pairs. So I've written the class this way:

class User {
    public $parameters;
    public function __construct($parameters) 
    {
        $this->parameters= $parameters;
    }
    public function __get($property) {
        return $parameters[$property];
    }
    ...
}

But it doesn't work as expected. The behaviour I want is:

$user= new User($params);
echo user.username;  // Searches in the parameters for the field "username"

Is possibile to do this?

Edit

With $user->username I get:

Notice: Undefined variable: parameters in /Library/WebServer/Documents/Cinema/blogics/user.php on line 10

Line 10 is the user __get method.

Was it helpful?

Solution

  • use $this->parameters[$property] instead of $parameters[$property] in the getter
  • call it $user->username
  • $parameters should be private to keep the encapsulation

In code

class User {
    private $parameters; // should be private (encapsulation)
    public function __construct($parameters)
    {
        $this->parameters= $parameters;
    }
    public function __get($property) {
        return $this->parameters[$property]; // instead of $parameters[$property]
    }
}

$params = array(
  "username" => "John Doe",
  "age" => 33
);

$user = new User($params);
echo $user->username; // -> instead of .

OTHER TIPS

You should declare username as class variable.

  public $username;

Then you can call username with user object as

   $user->username;

For more details about oops with PHP, you can check this link http://www.killerphp.com/tutorials/object-oriented-php/

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