PHP uses method overload to implement a get and set method for dynamically creating properties _javascript Tips

Source: Internet
Author: User
Tags php class

In PHP, we are not able to implement the method overload directly by means of the same method name, because PHP is a weak data type and is not a good way to distinguish between signatures. However, you can use the __call () method in the PHP class to implement the method overload. When a method that does not exist in a class is invoked, the __call () method is called automatically, in the form of __call ($name, $arguments) where $name is the name of the method, $arguments is an argument of an array type.

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

Copy Code code 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 (' 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 the Get Set method for each property.

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.