龙睿·LoRui
7十/110

PHP实现“属性”

一直觉得MS开发语言系列的对象“属性”很好,比起其他语言的getXXX和setXXX优雅的多。其实PHP是可以实现这个的——虽然大家在PHP里还是习惯了get/setXXX。PHP至少有两种方法实现
1、通过默认参数。
class User {
private $_name;

public function Name($value = NULL) {
if($value === NULL) { //get
return $this->_name;
} else { //set
$this->_name = $value;
}
}
}

$usr = new User;
$usr->Name = "龙睿";
echo $usr->Name;

2、通过魔法函数。
class Document {
private $_text;

public function __get($name) {
$method = "get$name";
return $this->$method();
}

public function __set($name, $value){
$method = "set$name";
return $this->$method($value);
}

public function getText() {
return $this->_text;
}

public function setText($text){
$this->_text = $text;
}
}
$doc = new Document;
$doc->Text = "LoRui.com";
echo $doc->Text;

热度: 1% [?]

相关日志

随机日志

评论 (0) 引用 (0)

还没有评论.


发表评论


还没有引用.