有数以千计的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;
我不知道你读过什么,但是我建议你阅读[官方手册页面(HTTP:// www.php.net/manual/en/language.oop5.overloading.php#object.get) - 因为很明显你不理解()'都需要其目的'__set()'和'__get。 –
在你的setter中,$ this - > $ property = $ value;需要$ this - > $ property = $ value [0]; –