Explanation of PHP Object Oriented Programming Overload (overloading) Operation

  • 2021-12-12 03:51:28
  • OfStack

This article illustrates the PHP object-oriented programming overload (overloading) operation. Share it 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 class methods with the same name, but each method has different parameter types and numbers. "Overloading" (overloading) provided by PHP means dynamically "creating" class properties and methods. Overloaded methods are called when class properties or methods that are undefined or invisible in the current environment are called. This is achieved by magic methods (magic methods).

1 Generally speaking, the member attributes in the class are defined as private, which is more in line with the realistic logic and can better protect the members in the class. However, read and assign operations to member attributes are very frequent, and it is very, very annoying to define public methods for each private attribute in the class that can be obtained and assigned outside the object. Therefore, in PHP after 5.1. 0, two methods "__get ()" and "__set ()" are predefined to get and assign values to all used private attributes, as well as the method "__isset ()" to check the existence of private attributes and the method "__unset ()" to delete private attributes from objects.
Generally speaking, overloading in php refers to 1 "processing mechanism" when an object or class uses its undefined or invisible properties and methods.

Attribute overload

When using an attribute that does not exist in an object, the pre-set response (handling mechanism) in this class.

Attribute, essentially a variable, has only four operations:

Value:

The method is automatically called when a "value" is taken on a property that does not exist (undefined or invisible) of an object: __GET() Method is case-insensitive.

Assignment:

When you "assign" a property that does not exist (undefined or invisible) on an object, the method is automatically called: __SET()

Judgment (isset):

When an isset () judgment is made on an object that does not exist (undefined or invisible), the method is automatically called: isset()

Destruction (unset):

When an unset () decision is made on an object's non-existent (undefined or invisible) property, the method is automatically called: unset()

The above four methods are called magic methods.

Magic method

__GET ($attribute name):

A method that is automatically called when "taking a value" for a nonexistent property of an object. The method can take a formal parameter to indicate the nonexistent property name (string) to be taken. This method can be used for some special treatment of unexpected situations.

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
?>

Overload of php, using __get() Method to "gracefully handle" the above errors.


<?php
class A{
  public $p1 = 1;
  //private $p2 = 1; // Here, the attributes are privatized, actually and undefined 1 Sample, to the outside is equivalent to non-existence 
  function __get($prop_name){
    /*
    // For example, it can be handled like this 
    echo "<br />{$prop_name} Attribute has not been defined (does not exist)! ";
    return ""; // You can also return 0 , or false Etc 
    */
    // You can also do this 
    trigger_error(" An error occurred: The attribute does not exist! ", E_USER_ERROR);
    die();
  }
}
$a1 = new A();
echo $a1->p1; //1
echo $a1->p2; // Undefined $p2 , but after " Deal with "
?>

Here is an example of an operation to get the private property used.

Examples:


<?php
class Person{
  public $name;
  public $sex;
  private $age; // Age privatization, this attribute cannot be accessed directly outside the class 
  function __construct($name='', $sex='', $age){
    $this->name = $name;
    $this->sex = $sex;
    $this->age = $age;
  }
  private function __get($propertyName){ // It needs to be used here private Decoration to prevent external calls to the class 
    if($propertyName == 'age'){
      return $this->age;
    }
  }
}
$p = new Person('yeoman', ' Male ',23);
$v1 = $p->name;
$v2 = $p->sex;
$v3 = $p->age;  // Automatically called __get() Method to get private properties age (Returned in function definition) 
echo "name=$v1, sex=$v2, age=$v3";
?>

The running result is:

name=yeoman, sex=Male, age=23

__SET ($attribute name, value):

When "assigning" an attribute that does not exist in an object, this internal magic method will be automatically called; It has two formal parameters, which represent the "property name" and "property value" to assign values to non-existent properties.
This method, combined with the _ GET method, often makes the class we define have an extensible feature. That is, the attributes of classes or objects can be more convenient and free.

Examples:


<?php
class A{
  // Definition 1 Attributes, 
  protected $prop_list = array();  // Initially empty array 
  // This method will be used in A Use the object of 1 Called when assigning a value to a property that does not exist 
  function __set($p,$v){
    //echo " Use non-existent attributes! ";
    $this->prop_list[$p] = $v;
  }
  function __get($p){
    return $this->prop_list[$p];
  }
}
$a1 = new A();
$a1->p1 = 1;  // Property name assignment that does not exist, at this time, the _set() , and pass it on "p1" And 1
$a1->p2 = 2;
$a1->ac = 'avc';
echo "<br /> Output the values of these "nonexistent attributes": ";
echo "<br />a1->p1:" . $a1->p1;  // Value of the property name that does not exist, at this time, it will be called _get() , and pass it on "p1"
echo "<br />a1->p2:" . $a1->p2;
echo "<br />a1->ac:" . $a1->ac;
?>

The running result is:

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

__ISSET ($attribute name):

When a property that does not exist in an object is executed isset() When judging, the internal method is automatically called: isset() ;

Usage:


$v1 = isset($ Object -> Attributes that do not exist );  // The magic method in the class to which this object belongs is called: isset()

Examples:


<?php
class A{
  // Definition 1 Attributes, 
  protected $prop_list = array();  // Initially empty array 
  // This method will be used in A Use the object of 1 Called when assigning a value to a property that does not exist 
  function __set($p,$v){
    //echo " Use non-existent attributes! ";
    $this->prop_list[$p] = $v;
  }
  function __get($p){
    if($this->prop_list[$p]){
      return $this->prop_list[$p];
    }else{
      return " The attribute does not exist! ";
    }
  }
  function __isset($prop){  //__isset() Is a custom method , isset() Is a system function 
    $re = isset($this->prop_list[$prop]);
    return $re;
  }
}
$a1 = new A();
$a1->p1 = 1;// Property name assignment that does not exist, at this time, the _set() , and pass it on "p1" And 1
$a1->p2 = 2;
$a1->ac = 'avc';
echo "<br /> Output the values of these "nonexistent attributes" ";
echo "<br />a1->p1:" . $a1->p1;// Value of the property name that does not exist, at this time, it will be called _get() , and pass it on "p1"
echo "<br />a1->p2:" . $a1->p2;
echo "<br />a1->ac:" . $a1->ac;
// The following demonstration isset Determine non-existent attributes 
$v1 = isset($a1->p1); // Existence 
$v2 = isset($a1->ppp1);  // Nonexistent 
var_dump($v1);
echo "<br />";
var_dump($v2);
?>

Run 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 a property that does not exist in an object is executed unset() When destroyed, the internal method is automatically called: unset() ;


<?php
class A{
  // Definition 1 Attributes, 
  protected $prop_list = array();  // Initially empty array 
  // This method will be used in A Use the object of 1 Called when assigning a value to a property that does not exist 
  function __set($p,$v){
    //echo " Use non-existent attributes! ";
    $this->prop_list[$p] = $v;
  }
  function __get($p){
    if($this->prop_list[$p]){
      return $this->prop_list[$p];
    }else{
      return " The attribute does not exist! ";
    }
  }
  function __unset($prop){
    unset($this->prop_list[$prop]);
  }
}
$a1 = new A();
$a1->p1 = 1;// Property name assignment that does not exist, at this time, the _set() , and pass it on "p1" And 1
echo "<br />a1->p1:" . $a1->p1;// Value of the property name that does not exist, at this time, it will be called _get() , and pass it on "p1"
// The following demonstration unset Destruction 1 Attributes that do not exist 
unset($a1->p1);
echo "<br />a1->p1:" . $a1->p1;
?>

The running result is:

a1- > p1:1
a1- > p1: This attribute does not exist!

In the following example, declare an Person class and set all member properties to private. Add a custom "in the class __isset() "And" __SET()0 "Two methods. Used outside the class" isset() "And" unset() "Function, these two methods are automatically called. The code is as follows:


<?php
class Person{
  private $name; // This property is sealed 
  private $sex;
  private $age;
  function __construct($name='', $sex=' Male ', $age){
    $this->name = $name;
    $this->sex = $sex;
    $this->age = $age;
  }
  private function __isset($propertyName){  // Need 1 Parameter, which is the name of the private attribute measured 
    if($propertyName == 'name'){
      return false;  // Returns false, not allowed to be measured outside the class name Attribute 
    }
    return isset($this->$propertyName);  // Here propertyName To add $ Character , Because this is a parameter, not an attribute 
  }
  private function __unset($propertyName){
    if($propertyName == 'name')
      return; // Exit the method, and it is not allowed to delete the name Attribute 
    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 ", 23);
var_dump(isset($person->name));  // Output bool(false) , not allowed to be measured name Attribute 
var_dump(isset($person->sex)); // Output bool(true) , exist sex Private attribute 
var_dump(isset($person->age)); // Output bool(true) , exist age Private attribute 
var_dump(isset($person->id)); // Output bool(false) Does not exist in the measured object id Attribute 
unset($person->name); // Delete private attributes name , but in  __unset() Deletion is not allowed in 
unset($person->sex);  // Delete a private property from an object sex , deletion succeeded 
unset($person->age);
$person->say();  // Object in the sex And age Property is deleted, output: Name: yeoman , sex:, age: 
?>

Run results:

boolean false
boolean true
boolean true
boolean false
Name: yeoman, Sex:, Age:

Method overload

When a "call" is made to an instance method of an object that does not exist, the __call() This magic method;

When you make a "call" to a static method that does not exist in the class, it will automatically call the __callstatic() This magic method.

Example: Call a nonexistent method directly


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

Errors will be reported, and the contents of errors will be:

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

Make "elegant treatment" of the above reported errors:


<?php
class A{
  // This method is automatically called when calling a strength method that does not exist for the object of this class 
  // This method must take 2 Parameters: 
  //$methodName: Represents a nonexistent method name to call; 
  //$argument: Indicates the real argument to be used when calling the nonexistent method, which is 1 An array of. 
  function __call($methodName, $argument){
    //echo "__call Has been called! ";
    echo $methodName . "() Method does not exist! ";
  }
}
$a = new A();
$a->f1(); // A nonexistent method , But after treatment, 
?>

The running result is:

f1 () method does not exist!

When you make a "call" to a static method that does not exist in the class, it will automatically call the __callstatic() This magic method. Similar to the above processing.

More readers interested in PHP can check out the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: