Ec (2); Author: the usage of Lao Wang GetterSetter is very common in the Java Community. For example, in EntityBean or DTO, this is sometimes necessary and sometimes boring. The Php community generally follows the pace of the Java Community, so many people inherit this practice ideologically. Let's take a look at the most common PHP practices: classDemo {& nbsp; pri script ec (2); script
Author: Lao Wang
The usage of Getter/Setter is very common in the Java Community. For example, in Entity Bean or DTO, It is necessary sometimes and boring sometimes. The Php community generally follows the pace of the Java Community, so many people inherit this practice ideologically.
Let's take a look at the most common PHP practices:
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 magic methods like _ call, if you have many 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];
&