2013-09-25 38 views
2

有数以千计的PHP __get的例子和__set在那里,可惜没有人真正告诉你如何使用它们。使用通用的getter和setter用PHP

所以我的问题是:我怎么实际使用对象时,从类中并调用__get和__set方法。

示例代码:

class User{ 
public $id, $usename, $password; 

public function __construct($id, $username) { 
     //SET AND GET USERNAME 
} 

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 User(1, 'Bastest'); 
// echo GET THE VALUE; 

我将如何设置构造函数中的价值观和我怎么才能在// echo GET THE VALUE;

+1

我不知道你读过什么,但是我建议你阅读[官方手册页面(HTTP:// www.php.net/manual/en/language.oop5.overloading.php#object.get) - 因为很明显你不理解()'都需要其目的'__set()'和'__get。 –

+0

在你的setter中,$ this - > $ property = $ value;需要$ this - > $ property = $ value [0]; –

回答

6

此功能称为在PHP overloading值。由于documentation__get__set方法将被调用,如果你试图访问不存在或不可访问的性能。你的代码中的问题是,你正在访问的属性是存在和可访问的。这就是为什么__get/__set不会被调用。

检查这个例子:

class Test { 

    protected $foo; 

    public $data; 

    public function __get($property) { 
     var_dump(__METHOD__); 
     if (property_exists($this, $property)) { 
      return $this->$property; 
     } 
    } 

    public function __set($property, $value) { 
     var_dump(__METHOD__); 
     if (property_exists($this, $property)) { 
      $this->$property = $value; 
     } 
    } 
} 

测试代码:

$a = new Test(); 

// property 'name' does not exists 
$a->name = 'test'; // will trigger __set 
$n = $a->name; // will trigger __get 

// property 'foo' is protected - meaning not accessible 
$a->foo = 'bar'; // will trigger __set 
$a = $a->foo; // will trigger __get 

// property 'data' is public 
$a->data = '123'; // will not trigger __set 
$d = $a->data; // will not trigger __get 
+0

谢谢,我认为这是它,并尝试它。问题当然是我的例子中的公共变量应该是私人的,包括在你的答案中,我会接受它。 – inControl

+1

已经更新吧:) – hek2mgl

+1

@inControl您也可以显式调用'$此 - > __集()'或'这本$ - > __得到()'。如果您从类内部访问受保护的属性,这很有趣 – hek2mgl