0

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);
?>

http://codepad.org/jwMaeVMN

Is there something that I am doing wrong here?

Community
  • 1
  • 1
Ryan Ward Valverde
  • 6,458
  • 6
  • 37
  • 48

3 Answers3

3

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;
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
1

To set:

$user->username = "user";

To get:

$username = $user->username;
1

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');
Marc B
  • 356,200
  • 43
  • 426
  • 500