Example of get and set methods for dynamically created properties in PHP

Source: Internet
Author: User
in PHP, we are not able to implement method overloading directly by signing different methods with the same method name, because PHP is weakData type , the signature cannot be distinguished well. However, you can implement method overloading by using the call () method in a class in PHP. When a method that does not exist in a class is called, the call () method is automatically called, in the form of call ($name, $arguments) where $name is the name of the method, $arguments is an array-type parameter.

The following example uses PHP's method overloads to dynamically create the get and set methods. (in object-oriented programming, a property in a class uses get and set to assign a value, but if there are too many properties in a class, such as 30, then if you do not use the method overload, we need to write 30 set methods, 30 get methods, self side slowly write it ... )

The code is as follows:

<?phpclass person{private $name; private $age; private $address; private $school; private $phonenum; public Function C All ($method, $args) {  $perfix =strtolower (substr ($method, 0,3));  $property =strtolower (substr ($method, 3));  if (Empty ($perfix) | | Empty ($property))  {   return;  }  if ($perfix = = "Get" &&isset ($this, $property)  {   return $this-$property;  }  if ($perfix = = "Set")  {   $this, $property = $args [0];  }} $p =new person (); $p->setname (' Lvcy '); $p->setage; $p->setaddress (Chengdu); $p->setschool (' UESTC '); $ P->setphonenum (' 123456 '); Echo $p->getname (). ' \\n '; Echo $p->getage (). ' \\n '; Echo $p->getaddress (). ' \\n '; Echo $p->getschool (). ' \\n ';? >

The call () method solves this problem easily, rather than writing a Get set method for each property.

Related Article

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.