PHP uses method overload to implement the get and set methods for dynamic attribute creation. getset

Source: Internet
Author: User

PHP uses method overload to implement the get and set methods for dynamic attribute creation. getset

In PHP, we cannot directly overload methods by using methods with the same name and different signatures, because PHP is a weak data type and cannot distinguish signatures. However, you can use the _ call () method in the PHP class to implement method overloading. 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) $ name is the method name, and $ arguments is an array type parameter.

The following example uses PHP method overload to dynamically create get and set methods. (In object-oriented programming, get and set are used to assign values to attributes in a class. However, if a class has too many attributes, such as 30, if method Overloading is not required, we need to write 30 set methods and 30 get methods, and write them slowly ...)

Copy codeThe Code is as follows:
<? Php
Class person
{
Private $ name;
Private $ age;
Private $ address;
Private $ school;
Private $ phonenum;
Public function _ call ($ 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 (23 );
$ P-> setAddress (chengdu );
$ P-> setschool ('uestc ');
$ P-> setphonenum ('000000 ');
Echo $ p-> getname (). '\ n ';
Echo $ p-> getage (). '\ n ';
Echo $ p-> getaddress (). '\ n ';
Echo $ p-> getschool (). '\ n ';
?>

The _ Call () method can easily solve this problem, rather than writing the get set Method for each attribute.

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.