PHP Object-Oriented Programming Overloading Operation

Time:2019-8-13

This paper gives an example of PHP object-oriented programming overloading operation. Share for your reference, as follows:

heavy load

“Overload” in PHP is different from most other object-oriented languages except that they all use the same noun. Traditional “overloading” is used to provide multiple classes with the same name, but the parameters of each method are different in type and number. The “overloading” provided by PHP refers to the dynamic “creation” of class attributes and methods. When calling the current environmentUndefinedorInvisibleOverloaded methods are called when class attributes or methods are used. It is achieved by magic methods.

Generally speaking, the member attributes in a class are defined as private, which is more in line with the logic of reality and can better protect the members of a class. However, it is very frequent to read and assign member attributes, and it is very troublesome to define public methods that can be acquired and assigned outside the object for each private attribute in the class. Therefore, in versions after PHP 5.1.0, two methods “_get()” and “_set()” are predefined to complete the operation of obtaining and assigning all the private attributes used, as well as the method “_isset()” used to check the existence of private attributes and the method “_unset()” used to delete private attributes in objects.
Popularly, overloading in PHP means that when an object or class uses its undefined or invisible attributes and methods, some of them are “processing mechanisms”.

Property Override

When an attribute that does not exist in an object is used, a pre-defined response (processing mechanism) in this class is provided.

Attribute is essentially a variable with only four operations:

Value:

When an object does not exist (undefined or invisible) attribute is “valued”, the method is automatically invoked:__GET()Method is case-insensitive.

Assignment:

When an attribute of an object that does not exist (undefined or invisible) is “assigned”, the method is automatically invoked:__SET()

Isset:

When isset () judges an attribute that does not exist (undefined or invisible) on an object, the method is automatically invoked:isset()

Destruction (unset):

When unset () judges an attribute that does not exist in an object (undefined or invisible), the method is automatically invoked:unset()

These four methods are called magic methods.

Magic Methods

_ GET ($attribute name):

A method is called automatically when “value” is applied to an attribute that does not exist in an object. The method can take a parameter to indicate the attribute name (string) that does not exist in order to get the value. This method can be used to deal with unexpected situations in a special way.

For example:

<?php
class A{
  public $p1 = 1;
}
$a1 = new A();
echo $a1->p1; //1
Echo $a1 - > p2; // undefined $p2, will report an error, Notice: Undefined property: A:: $p2
?>

PHP overload, using__get()Method “graceful handling” of the above errors.

<?php
class A{
  public $p1 = 1;
  // Private $p2 = 1; // Privatization of attributes here, which, like undefined, is externally equivalent to nonexistence
  function __get($prop_name){
    /*
    // For example, you can do this.
    Echo "<br/>{$prop_name} attribute has not been defined (does not exist)!" ";
    Return ";// Can also return 0, or false, etc.
    */
    // You can also do this.
    Trigger_error ("Error: Attribute does not exist! "(E_USER_ERROR);
    die();
  }
}
$a1 = new A();
echo $a1->p1; //1
Echo $a1 - > p2; // undefined $p2, but processed
?>

Here is an example of an operation to obtain the private attributes used.

Example:

<?php
class Person{
  public $name;
  public $sex;
  Private $age; // age privatization, no direct access to this property outside the class
  function __construct($name='', $sex='', $age){
    $this->name = $name;
    $this->sex = $sex;
    $this->age = $age;
  }
  Private function get ($propertyName) {/// Here, use private modifier to prevent external class calls
    if($propertyName == 'age'){
      return $this->age;
    }
  }
}
$p = new Person ('yeoman','man', 23);
$v1 = $p->name;
$v2 = $p->sex;
$v3 = $p - > age; // automatically calls the _get() method to get the private property age (returned in the function definition)
echo "name=$v1, sex=$v2, age=$v3";
?>

The results are as follows:

Name = yeoman, sex = male, age = 23

_ SET ($attribute name, value):

When assigning an attribute that does not exist to an object, this internal magic method is automatically invoked; it has two parameters, representing the “attribute name” and “attribute value” of assigning an attribute that does not exist.
This method, combined with the _GET method, can often make the classes we define have an extensible feature. That is, the attributes of classes or objects can be more convenient and free.

Example:

<?php
class A{
  // Define an attribute.
  Protected $prop_list = array (); // Initially empty array
  // This method is called when the object of A is assigned with a nonexistent attribute.
  function __set($p,$v){
    // echo "Use nonexistent attributes! ";
    $this->prop_list[$p] = $v;
  }
  function __get($p){
    return $this->prop_list[$p];
  }
}
$a1 = new A();
$a1 - > P1 = 1; // assignment of non-existent attribute names, at which point _set() is called and passed to "p1" and "1"
$a1->p2 = 2;
$a1->ac = 'avc';
Echo "<br/> outputs the values of these"nonexistent attributes";
Echo "< br /> A1 - > p1:" $A1 - > p1; // the value of the attribute name that does not exist is called _get () and passed to "p1"
echo "<br />a1->p2:" . $a1->p2;
echo "<br />a1->ac:" . $a1->ac;
?>

The results are as follows:

Output the values of these “nonexistent attributes”:
a1->p1:1
a1->p2:2
a1->ac:avc

_ ISSET ($attribute name):

When an attribute does not exist for an objectisset()When judged, internal methods are automatically invoked:isset();

Usage:

$v1 = isset ($object - > nonexistent attribute); // The magic method in the class to which the object belongs is called at this time: isset ()

Example:

<?php
class A{
  // Define an attribute.
  Protected $prop_list = array (); // Initially empty array
  // This method is called when the object of A is assigned with a nonexistent attribute.
  function __set($p,$v){
    // echo "Use nonexistent attributes! ";
    $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 and isset () is a system function
    $re = isset($this->prop_list[$prop]);
    return $re;
  }
}
$a1 = new A();
$a1 - > P1 = 1; // Assignment of non-existent attribute names calls _set() and passes "p1" and "1"
$a1->p2 = 2;
$a1->ac = 'avc';
Echo "<br/> outputs the values of these"nonexistent attributes";
Echo "< br /> A1 - > p1:" $A1 - > p1; // the value of a non-existent attribute name is called at this time _get(), and passed to "p1"
echo "<br />a1->p2:" . $a1->p2;
echo "<br />a1->ac:" . $a1->ac;
// Here's a demonstration of isset's judgement of non-existent attributes
$v1 = isset ($a1 - > p1); // Existence
$v2 = isset ($a1 - > ppp1); // nonexistent
var_dump($v1);
echo "<br />";
var_dump($v2);
?>

Operation results:

Output the values of these “nonexistent attributes”
a1->p1:1
a1->p2:2
a1->ac:avc
boolean true
boolean false

_ UNSET ($attribute name)

When an attribute does not exist for an objectunset()When destroyed, internal methods are automatically invoked:unset();

<?php
class A{
  // Define an attribute.
  Protected $prop_list = array (); // Initially empty array
  // This method is called when the object of A is assigned with a nonexistent attribute.
  function __set($p,$v){
    // echo "Use nonexistent attributes! ";
    $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]);
  }
}
$a1 = new A();
$a1 - > P1 = 1; // Assignment of non-existent attribute names calls _set() and passes "p1" and "1"
Echo "< br /> A1 - > p1:" $A1 - > p1; // the value of a non-existent attribute name is called at this time _get(), and passed to "p1"
// Here's a demonstration of unset destroying a non-existent property
unset($a1->p1);
echo "<br />a1->p1:" . $a1->p1;
?>

The results are as follows:

a1->p1:1
A1 – > p1: This property does not exist!

In the following example, declare a Person class and set all member properties to private. Add custom to the class“__isset()” and“__unset()” Two methods. Use outside the class“isset()” and“unset()” These two methods are called automatically when the function is used. The code is as follows:

<?php
class Person{
  Private $name; // This property is blocked
  private $sex;
  private $age;
  Function _construct ($name=', $sex='man', $age){
    $this->name = $name;
    $this->sex = $sex;
    $this->age = $age;
  }
  Private function _isset ($propertyName) {// Requires a parameter, which is the name of the private attribute determined
    if($propertyName == 'name'){
      Return false; // Return false, not allowing the name attribute to be determined outside the class
    }
    Return isset ($this - > $propertyName); // Here propertyName needs to add a $character, because this is a parameter, not an attribute
  }
  private function __unset($propertyName){
    if($propertyName == 'name')
      Return; // Exit method, which does not allow deletion of the name attribute in the object
    Unset ($this - > $propertyName); // Here propertyName is added with a $character
  }
  public function say(){
    Echo: "Name:" $this - > name. ", $this - > sex.", $this - > age. "<br />";
  }
}
$person = new Person ("yeoman", "man", 23);
Var_dump (isset ($person - > name); // output bool (false), not allowing the determination of name attribute
Var_dump (isset ($person - > sex); // output bool (true), with sex private attributes
Var_dump (isset ($person - > age); // output bool (true), with age private attributes
Var_dump (isset ($person-> id)); // output bool (false), no ID attribute exists in the measured object
Unset ($person - > name); // Delete the private attribute name, but it is not allowed to delete in _unset ()
Unset ($person - > sex); /// Delete the private property sex in the object successfully
unset($person->age);
Person - > say (); // The sex and age attributes in the object are deleted and output: name: yeoman, gender: age:
?>

Operation results:

boolean false
boolean true
boolean true
boolean false
Name: yeoman, gender: age:

Overload

When an instance method that does not exist for an object is called, the class is automatically called__call()This magic method;

When a static method that does not exist in a class is called, it automatically calls the method in the class.__callstatic()This magic trick.

Example: Direct invocation of non-existent methods

<?php
ini_set('display_errors',1);
class A{
}
$a = new A();
$a - > F1 (); // non-existent method
?>

Errors will be reported. The contents of the errors are as follows:

Fatal error: Uncaught Error: Call to undefined method A::f1()

“Elegant handling” of the above mistake:

<?php
class A{
  // This method is automatically invoked when a powerful method that does not exist for the object of this class is invoked.
  // This method must take two parameters:
  // methodName: The name of the non-existent method to be invoked;
  // argument: An array of real parameter data is used to invoke a method that does not exist.
  function __call($methodName, $argument){
    // echo "_call is called! ";
    Echo $methodName. "() method does not exist! ";
  }
}
$a = new A();
$a - > F1 (); // / nonexistent method, but processed
?>

The results are as follows:

F1 () method does not exist!

When a static method that does not exist in a class is called, it automatically calls the method in the class.__callstatic()This magic trick. Similar to the above processing.

More readers interested in PHP-related content can see the topics of this site: Introduction to Php Object-Oriented Programming, Introduction to PHP Array Operating Skills, Introduction to PHP Basic Grammar, Summary of PHP Operating and Operator Usage, Summary of Php String Usage, and php+mysql Data. Introduction to Library Operations and Summary of Common Database Operating Skills in PHP

I hope this article will be helpful to everyone’s PHP program design.