PHP Object-oriented-detailed description of the example code for overloading (overloading)

Source: Internet
Author: User

Overload

"Overloading" in PHP differs from most other object-oriented languages, except that they all use the same noun. Traditional "overloads" are used to provide multiple class methods with the same name, but each method has a different parameter type and number. PHP provides a "reload" (overloading) that refers to the dynamic "create" class properties and methods. Overloaded methods are called when a class property or method is called that is undefined or not visible under the current environment. is achieved by means of magic methods.
In general, the definition of a member attribute in a class as private, which is more realistic logic, can better protect the members of the class. However, read and assignment operations on member properties are very frequent, and it is very annoying if you define public methods in your class that can be fetched and assigned outside of the object for each private property. Therefore, in later versions of PHP5.1.0, two methods "get ()" and "set ()" were predefined to complete the operation of obtaining and assigning the private properties used, and the method "Isset ()" To check for the existence of a private property and to remove the private attribute method in the object unset ( )”。
In layman's terms, overloading in PHP means that when an object or class uses its undefined or invisible properties and methods, some of these "processing mechanisms".

Property overloading

When using a property that does not exist for an object, the workaround (processing mechanism) is pre-set in this class.
property, which is essentially a variable, has only 4 operations:

Value:

The method is called automatically when a property that does not exist (undefined or invisible) is "evaluated": The GET () method is not case-sensitive.

Assignment value:

The method is called automatically when an attribute that does not exist (undefined or invisible) is assigned to an object: SET ()

Judgment (Isset):

The method is called automatically when a property that does not exist (undefined or invisible) is isset () on an object: Isset ()

Destruction (unset):

The method is automatically called when a unset () property is determined for an object that does not exist (undefined or invisible): unset ()

The above 4 methods are called magic methods.

Magic method

GET ($ property name):

When a property that does not exist for an object is "valued", the method is called automatically, where the method can take a formal parameter that represents a property name (string) that is to be evaluated without being present, and this method can be used to perform some special processing of the unexpected case.

For example:

<?phpclass a{    public  $p 1 = 1;} $a 1 = new A (); Echo $a 1->p1;  1echo $a 1->p2;//undefined $p2, will error, notice:undefined property:a:: $p 2?>

PHP overloads, use the Get () method to "gracefully handle" the error above.

<?php<?phpclass a{    public  $p 1 = 1;        Private $p 2 = 1;      This property is privatized, in fact, as undefined, for the outside is equivalent to the absence of    function get ($prop _name) {        /////For example, can handle        echo "<br/>{$prop _name} property is undefined (not present)! ";        Return "";  can also return 0, or FALSE, etc.///        can also handle        trigger_error ("An error occurred: The property does not exist!") ", e_user_error);                Die ();    }} $a 1 = new A (); Echo $a 1->p1;  1echo $a 1->p2;//undefined $p2, but "processed"?>

Here is an example of the operation taken with the private property used.
 
Example:

<?phpclass person{public    $name;      public $sex;        Private $age;  Age privatization, outside the class can not directly access this property        function construct ($name = ", $sex =", $age) {        $this->name = $name;                $this->sex = $sex;                $this->age = $age;       }    Private function Get ($propertyName) {//This is to be decorated with private, to prevent calls outside the class        ($propertyName = = ' age ') {                    return $this Age;}}    } $p = new Person (' yeoman ', ' Male ', at->name;), $v 1 = $p $v 2 = $p->sex; $v 3 = $p->age;    The Get () method is called automatically to get the private property of age (return inside function definition) echo "name= $v 1, sex= $v 2, age= $v 3";? >

The result of the operation is:

Name=yeoman, sex= man, age=23

SET ($ property name, value):

This internal magic method is automatically called when an attribute that does not exist for an object is "assigned", and it has 2 parameters that represent the property name and property value that are assigned to the nonexistent property.
This method, combined with the _get method, often allows us to define classes that have an extensible feature. That is, the properties of a class or object can be more convenient and free.

Example:

<?phpclass a{    //Define an attribute,    protected $prop _list = Array ();        Initial empty array    //This method invokes the    function set ($p, $v) {//echo "using a nonexistent property when the object of a is assigned with a nonexistent property        !). ";        $this->prop_list[$p] = $v;         }    function Get ($p) {        return $this->prop_list[$p];        }} $a 1 = new A (), $a 1->p1 = 1;   A non-existent property name assignment, which calls _set () and passes through "P1" and 1$a1->p2 = 2; $a 1->ac = ' AVC '; Echo ' <br/> Outputs these "nonexistent properties" values: "; echo" <BR/ >A1->P1: ". $a 1->p1;    The value of the nonexistent property name is called _get () and passed through "P1" echo "<br/>a1->p2:". $a 1->p2;echo "<br/>a1->ac:". $a 1->ac;? >

The result of the operation is:

Output values for these "non-existent properties": A1->P1:1A1->P2:2A1->AC:AVC

ISSET ($ property name):

An internal method is called automatically when a property that does not exist for an object is Isset (): Isset ();

Usage:

$v 1 = isset ($ object-no property exists);    This will invoke the Magic method in the class that this object belongs to: Isset ()

Example:

<?phpclass a{    //Define an attribute,    protected $prop _list = Array ();    Initial empty array    //This method invokes the    function set ($p, $v) {//echo "using a nonexistent property when the object of a is assigned with a nonexistent property        !). ";        $this->prop_list[$p] = $v;         }    function Get ($p) {        if ($this->prop_list[$p]) {            return $this->prop_list[$p];        } else{            Return "This property does not exist! ";        }    }    function Isset ($prop) {   //isset () is a custom method, Isset () is a system function        $re = isset ($this->prop_list[$prop]);        return $re;    }} $a 1 = new A (), $a 1->p1 = 1;//does not exist for the property name assignment, the _set () is called and passes through "P1" and 1$a1->p2 = 2; $a 1->ac = ' AVC '; echo "<br/> Output these" do not The value of the existing property "; echo" <br/>a1->p1: ". $a 1->p1;//the value of a property name that does not exist, it calls _get () and passes through "P1" echo "<br/>a1->p2:". $a 1->p2;echo "<br/>a1->ac:". $a 1->ac;//below demonstrates isset to determine the non-existent properties $v1 = isset ($a 1->p1);  Presence $v2 = Isset ($a 1->ppp1);    No Var_dump ($v 1); echo "<br/>"; Var_dump ($v 2);? >

Operation Result:

Outputs the value of these "non-existent properties" A1->p1:1a1->p2:2a1->ac:avcboolean Trueboolean false

UNSET ($ property name)

An internal method is automatically called when a property that does not exist for an object is unset () destroyed: unset ();

<?phpclass a{    //Define an attribute,    protected $prop _list = Array ();        Initial empty array    //This method invokes the    function set ($p, $v) {//echo "using a nonexistent property when the object of a is assigned with a nonexistent property        !). ";        $this->prop_list[$p] = $v;         }    function Get ($p) {        if ($this->prop_list[$p]) {                    return $this->prop_list[$p];        } else{                    Return "This property does not exist! ";        }    }    function unset ($prop) {        unset ($this->prop_list[$prop]);}     } $a 1 = new A (), $a 1->p1 = 1;//does not exist for the property name assignment, this calls _set () and passes through "P1" and 1echo "<br/>a1->p1:". $a 1->p1;//the value of a property name that does not exist, it calls _get () and passes through the "P1"//shown below unset destroys a nonexistent property unset ($a 1->p1); echo "<br/>a1->p1:". $a 1->p1;? >

The result of the operation is:

A1->P1:1A1->P1: The property does not exist!

In the following example, declare a person class and set all the member properties to private. Add Custom "Isset ()" and "unset ()" Two in a class. Both methods are called automatically when you use the Isset () and unset () outside of the class. The code is as follows:

<?phpclass person{private $name;//This property is blocked by private $sex;    Private $age;        function __construct ($name = ', $sex = ' male ', $age) {$this->name = $name;        $this->sex = $sex;      $this->age = $age;  } Private Function __isset ($propertyName) {//requires a parameter that is the name of the measured private property if ($propertyName = = ' name ') {return   False   Returns false, does not allow the Name property to be measured outside the class} return Isset ($this-$propertyName); Here PropertyName to add the $ character, because this is the argument, not the property} Private Function __unset ($propertyName) {if ($proper Tyname = = ' name ') return;  The exit method does not allow the deletion of the name attribute in the object unset ($this, $propertyName); Here PropertyName to add $ character} public function say () {echo "name:". $this->name. ", Gender:". $this->sex. ", Age:". $this->age.     "<br/>";    }} $person = new person ("Yeoman", "male", "Var_dump"); (Isset ($person->name)); output bool (false), does not allow the determination of the name attribute Var_dump (isset ($person->sex)); output bool (TRUE), there is a sex private attribute Var_dump (ISSET ($person->age));  output bool (TRUE), there is an Age private attribute Var_dump (Isset ($person->id));  output bool (FALSE), the id attribute unset ($person->name) does not exist in the measurement object;   Delete the private property name, but __unset () is not allowed to delete unset ($person->sex);    Delete Private property in object sex, delete success unset ($person->age); $person->say (); The sex and age attributes in the object are deleted, output: Name: Yeoman, Gender:, ages:?>

Operation Result:

Boolean Falseboolean Trueboolean Trueboolean false name: Yeoman, Gender:, Age:

Method overloading

Call () in a class is automatically called when a method of an instance that does not exist for an object is called.
The Magic Method of Callstatic () in a class is automatically called when a static method that does not exist for a class is called.

Example: calling a non-existent method directly

<?phpini_set (' display_errors ', 1); class a{} $a = new A (); $a->f1 ();  Non-existent method?>

will be error, the error content is:

Fatal error:uncaught error:call to undefined method a::f1 ()

"Graceful handling" of the above error:

<?phpclass a{    //When a power method that does not exist for this class object is called, the method is called automatically//    This method must have 2 formal parameters:    //$methodName: Indicates the non-existent method name to invoke;    /$argument: Indicates that the argument data used to invoke the non-existent method is an array.    function Call ($methodName, $argument) {        //echo "calls is called! ";        Echo $methodName. The () method does not exist! ";    }} $a = new A (); $a->f1 ();  Methods that do not exist, but are treated?>

The result of the operation is:

The F1 () method does not exist!

The Magic Method of Callstatic () in a class is automatically called when a static method that does not exist for a class is called. Similar to the above treatment.

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.