Compare PHP and Ruby Getter/setter implementations

Source: Internet
Author: User
Tags php and

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];
  &

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.