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.