Author: Lao Wang
Getter/setter usage is common in the Java community, such as in entity beans or DTO, which is sometimes necessary and sometimes tedious. The PHP community is generally crawling along the steps of the Java community, so many people have inherited this approach in their minds.
First look at the most common practice in 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;
}
}
Of course, because of the flexibility of the PHP scripting language, with the help of the magic method of __call, if you have a lot of attributes, we can write more easily:
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];
&