最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
对比Php和Ruby的getter/setter实现方式
时间:2008-04-24 编辑:简简单单 来源:一聚教程网
作者:老王
Getter/Setter的用法在Java社区里很常见,比如说在Entity Bean或者DTO中,这东西有的时候很必要,有的时候则乏味得很。Php社区一般都是跟着Java社区的步伐匍匐前进,所以很多人在思想上继承了这样的做法。
先看看PHP中最一般的做法:
class Demo {
private $name;
private $age;
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getAge() {
return $this->$age;
}
public function setAge($age) {
$this->age = $age;
}
}
当然,因为Php脚本语言的灵活性,借助__call这样的魔术方法,如果你的属性很多,我们可以写得更简便些:
class Demo {
private $name;
private $age;
public function __call($name, $args) {
if (preg_match(''/^(get|set)(w+)/'', $name, $match)) {
$firstChar = substr($match[2], 0, 1);
$lastChars = substr($match[2], 1);
$this->$attribute = strtolower($firstChar) . $lastChars;
if (''get'' == $match[1]) {
return $this->$attribute;
} else {
$this->$attribute = $args[0];
&
-
下一个: php注入方法集锦
相关文章
- PHP输入流 php://input与POST/GET的区别 04-27
- php报错file_get_contents(): php_network_getaddresses问题 09-05
- PHP Warning: file_get_contents failed to open stream解决办法 06-25
- php中func_get_arg,func_get_args,func_num_args实现伪重载 11-07
- php提示Warning: file_get_contents(): couldn’t resolve 07-05
- 解决php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution错误 05-02