作者:老王
Getter/Setter的用法在Java社区里很常见,比如说在Entity Bean或者DTO中,这东西有的时候很必要,有的时候则乏味得很。Php社区一般都是跟着Java社区的步伐匍匐前进,所以很多人在思想上继承了这样的做法。
先看看PHP中最一般的做法:
class Demo {
private $name;
private $age;
public function getName() {
return $this->name;
}
立即学习“PHP免费学习笔记(深入)”;
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在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号