Compare the getter/setter implementation methods of Php and Ruby-PHP source code

Source: Internet
Author: User
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];
&

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.