Reputation: 6737
According to this answer here: Getter and Setter? The following function should work, however it produces no output.
<?php
class UserInfo{
private $username;
private $privileges;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
$user=new UserInfo;
$user->__set($username,"someuser");
echo $user->__get($username);
?>
Is there something that I am doing wrong here?
Upvotes: 0
Views: 121
Reputation: 360642
When this line is called:
$user->__set($username,"someuser");
there is no $username in scope, and you're passing a null parameter into the method call.
The call should be
$user->__set('username', 'someuser');
Upvotes: 1
Reputation: 66
To set:
$user->username = "user";
To get:
$username = $user->username;
Upvotes: 1
Reputation: 449415
Your immediate problem is that you would have to use "username"
instead of the undefined $username
when passing the property name to the function.
However, this is not how magic getters and setters work in the first place. You're supposed to set using $user->username = "someuser";
that will automatically trigger the setter:
$user=new UserInfo;
$user->username = "someuser";
echo $user->username;
Upvotes: 3