当前位置:网站首页>PHP - Common magic method (nanny level teaching)

PHP - Common magic method (nanny level teaching)

2022-07-06 07:52:00 hcjtn

PHP—— Common magic methods

php Specify two underscores (__) The first methods are reserved as magic methods

php It's an object-oriented language , however Previous php Language is really not , So there are some object-oriented standard implementations that are not perfect , For example, overloading . But we can make up for it by some magic methods .

In many cases , When we create the member attribute of an object , It can only be determined at a certain moment , This is not allowed before or after , But we can't give our member attribute a function value ( Attribute does not support ), So at this time, we need a specific method -—— Magic technique

for example :

<?php
 class human{
    
    // Member attribute 
      var $name;
      var $sex
      function human(){
    
          echo '#########';  //echo()  Function outputs one or more strings .
      }
      function wawaku(){
    
          echo '555555555~';
      }
}
$one=new huamn;
var_dump($one);

When I When the method name is the same as the class name , As soon as I create $one=new huamn; This object , Will be output echo '#########' This is when it was created , So after , I add the following sentence :

<?php
 class human{
    
    // Member attribute 
      var $name;
      var $sex
       // Member method  
         // Magic methods 1: Construction method  
      function human(){
    
          echo '#########';
          $this->sex = mt_rand(0,1) ? ' male ':' Woman ';
      }
      function wawaku(){
    
          echo '555555555~';
      }
}
$one=new human;
var_dump($one);       //var_dump()  Function is used to output information about variables .

When there are parameters in my construction method ,

  function human($a)

So I $one There should also be a bracket after it , And fill in the corresponding parameters

$one=new human('a');

notes : This method is just an example , In real life, it is not recommended to use . Because once we change the class name , We have to put all human Change all to the same name , Otherwise, the construction fails

In real life , We use functions more often , for example __construct()

<?php
 class human{
    
    // Member attribute 
      var $name;
      var $sex
       // Member method  
       // Magic methods 1: Construction method  
      function __construct($name){
    
          $this->sex = mt_rand(0,1) ? ' male ':' Woman ';
          $this->name = $name;
      
      }
      function wawaku(){
    
          echo '555555555~';
      }
}
$one=new human('hcj');
var_dump($one);

therefore ,

Simply speaking , Magic method is a special function

Common magic functions

Construction method and analytical method

1.__construct()—— Construction method

__construct() It's a constructor

  • trigger : Instantiate in object ( Create objects ) It will trigger automatically when

  • effect : Initialize member properties

  • Parameters : There can be , There can be no , Depends on setting and logic

  • Return value : No,

  • Be careful : If the constructor has parameters , And the parameter has no default value , When instantiating an object , You must add arguments in parentheses after the class name

  • <?php
     class human{
          
        // Member attribute 
          var $name;
          var $sex;
          var $id;    
           // Member method  
           // Magic methods 1: Construction method  
          function __construct($name){
          
              $this->sex = mt_rand(0,1) ? ' male ':' Woman ';
              $this->name = $name;
              $this->id = uniqid();     //uniqid()  Generate a unique  ID
          }
          function wawaku(){
          
              echo '555555555~';
          }
    }
    $one=new human('hcj');
    var_dump($one);        
    

2. __desctruct()—— destructor

__desctruct() Destructor , Calls that don't need to be displayed , The system will call this method automatically . And destructors don't need parameters ( Because there is no need to call )

  • trigger : Automatically triggered when the object is destroyed (unset() perhaps Page execution complete )

  • effect : Recycle resources during the use of objects , coordination unset Use

  • Parameters : No,

  • Return value : No,

  • <?php
        class human {
          
          var $name;
          var $sex;
          var $id;
         function __construct($name){
          
              $this->sex = mt_rand(0,1) ? ' male ':' Woman ';
              $this->name = $name;
              $this->id = uniqid();     //uniqid()  Generate a unique  ID
          }
         function __destruct($name){
          
             echo '@@@@@@@@@@';
             unset($this->id);
         }
    }
     $one=new human('hcj');
     var_dump($one);
     unset($one);
    // notes : Here we cannot detect , Because at this time ,one Has been logged off , Can't view id situation 
    

** Three characteristics of object-oriented :

  • encapsulation
  • Inherit
  • polymorphic ( An idea )

Object oriented encapsulation features

  1. Package characteristics : After an object is generated , Some member properties and member methods of an object are logically not allowed to be called or used outside the object . This is the origin of packaging features

  2. Encapsulated keywords :private Private

    • private Characteristics of :

      1. By private Decorated member properties cannot be accessed outside the class , Can be accessed inside the class .
      2. By private Decorated member methods cannot be accessed outside the class , Can be accessed inside the class .
      3. var and private Only one... Can be selected ( Include public and protected )
      <?php
          var xiyiji {
              
          private $color = ' white ';
          var $pinpai = ' haier ';
          var $weight = '20kg';
          var $rongliang = '6.5L';
          private $mada = ' Mitsubishi Heavy Industries ';
          // Member method 
          // How to wash clothes 
          private function xiyi() {
              
                 echo ' Wash the clothes ';
                $this->settime();
          }
          private function tuoshui() {
              
               echo' dehydration ';
           
          }
       
         private function settime() {
              
                echo' Timing function ';
                 echo $this->mada.' Turn on the timing function ';
          }
      }
      // Instantiate a laundry object 
      $one= new xiyiji();
      var_dump($one);
      echo $one->xiyi();
      // Find that you can call ,  Mitsubishi Heavy Industries starts the timing function for washing clothes 
      // Try to modify  private  Decorated member attribute value 
      '''$one->made = ' Learning garden '; var_dump($one);'''
      // Find out about , Change failed , So we need magic to open a back door 
      // Magic methods  __get()
      
  3. Magic methods : __get( Access back door )

    • trigger : Automatically triggered when accessing private member properties
    • function :1. Prevent error reporting 2. Provide a back door for private member property access
    • Parameters : One Access private member attribute name
    • Return value : There can be , There can be no , The actual situation determines
    • Be careful :__get Functions can only be viewed and cannot be modified .
   <?php
    var xiyiji {
    
    // Member attribute 
    private $color = ' white ';
    var $pinpai = ' haier ';
    var $weight = '20kg';
    var $rongliang = '6.5L';
    private $mada = ' Mitsubishi Heavy Industries ';
    // Member method 
    // How to wash clothes 
    private function xiyi() {
    
           echo ' Wash the clothes ';
          $this->settime();
    }
    private function tuoshui() {
    
         echo' dehydration ';
     
    }
 
   private function settime() {
    
          echo' Timing function ';
           echo $this->mada.' Turn on the timing function ';
           
    }
    function __get($pro) {
         //__get  When I call private member properties , This method will be called , But not all private member attributes I need to see , So there should be a judgment 
       if($pro == 'name'){
    
        echo '######';
       // echo $this->color;
        return $this->$pro;
       }else{
    
           return ' Prohibit viewing ';
       }
        
    }
}
// Instantiate a laundry object 
$one= new xiyiji();
var_dump($one);
echo $xiyiji->color;
echo  '<hr/>';
echo $xiyi->settime;
//xiyiji->color='red';  Found that the failure 
  1. Magic methods : __set()
    • Departure time : Automatically triggered when setting the value of the private member property
    • function :1. Shielding error 2. Provide a back door for private member property settings
    • Parameters : Two $a The original value of the private member property $b New value of private member property
    • Return value : no return value
<?php
    class Person {
    
    // Member attribute 
    var $name = ' Li Lanying ';
    private $sex = ' male ';
    var $age = '38';
    // Member method 
    function say(){
    
        echo ' Buddha is auspicious ';
    }
      function nn(){
    
        echo ' Hua Lala ~';
      }
    // Magic methods  __set($a,$b){ $a  The original value of the private member property  $b  New value of private member property 
    function __set($a,$b){
    
        if($pro == 'sex'){
    
        echo '##';
       //var_dump($a);
       //var_dump($b);
        $this->$a = $b
        }else{
    
         echo  ' No modification  ';
            // no return value 
        }
    }
}
         
}
  // Instantiate objects 
    $lly = new Person;
    var_dump($lly);
 //  Access private member properties 
 // echo $lly->sex; 
 //  Set private member properties 
  $lly->sex = ' Simon? ';
  var_dump($lly);

  1. Magic methods :__isset
    • trigger : Modify the private member attribute isset Automatically trigger when checking
    • function : Instead of outside the object isset Function detection , Return results
    • Parameters :1 individual , Private member attribute name
    • Return value : Generally return to isset() Examination result
<?php
    class Person {
    
    // Member attribute 
    var $name = ' Li Lanying ';
    private $sex = ' male ';
    var $age = '38';
    // Member method 
    function say(){
    
        echo ' Buddha is auspicious ';
    }
      function nn(){
    
        echo ' Hua Lala ~';
      }
    // Magic methods  __set($a,$b){ $a  The original value of the private member property  $b  New value of private member property 
    function __set($a,$b){
    
        if($pro == 'sex'){
    
        echo '##';
       //var_dump($a);
       //var_dump($b);
        $this->$a = $b
        }else{
    
         echo  ' No modification  ';
            // no return value 
        }
}
    function __isset(){
    
        echo '######';
        var_dump($pro);
       // return isset($this->$pro);
        
    }
         
}
  // Instantiate objects 
    $lly = new Person;
  // Check whether the name attribute is set   Non private 
  //$result = isset($lly->name);
  //var_dump($result); ture 
  // External  isset  Cannot detect private member properties   The return value is  false
  ''' Check private properties '''
   $result = isset($lly->sex);    
  var_dump($result)
  1. Magic methods :__unset

    • trigger : Modify the private member attribute unset Automatically trigger when checking
    • function : Instead of outside the object unset Function detection ,
    • Parameters :1 individual , Private member attribute name
    • Return value : nothing
<?php
    class Person {
    
    // Member attribute 
    var $name = ' Li Lanying ';
    private $sex = ' male ';
    var $age = '38';
    // Member method 
    function say(){
    
        echo ' Buddha is auspicious ';
    }
      function nn(){
    
        echo ' Hua Lala ~';
      }


     function __unset(){
    
         //var_dump($a);
         if($pro == 'sex'){
    
           unset($this->$pro);  
         }
     }
}
  // Instantiate objects 
    $lly = new Person;
  // Delete an attribute   Non private 
   ''' unset($lly->name); var_dump($lly);'''
 // Delete a private member attribute 
   unset($lly->sex);;
   var_dump($lly)   


Object oriented inheritance features

  1. Inheritance features :

    • Inheritance format :

      • class Class name extends Father's name {

        ​ The unique method of writing subclass and human writing ;

        }

    • Concept :

      • father : Interpreted parent class inherited by other classes , Also called base class ;
      • Subclass : A class that inherits from other classes is a subclass , Also called derived classes .
    • characteristic :

      1. The subclass inherits the parent class, which has both the All member properties and methods ( private private Except for )

      2. After inheriting the parent class, a subclass can have properties and methods unique to the subclass .

        Grandpa has Father, too Father has Grandpa may not have

      3. On inheritance , Subclasses allow methods with the same name as the father , This situation will not conflict , Instead, the methods of the subclass will override the methods of the parent class , This method is called overloading ( Reload ).

      4. ​ Magic methods can be inherited by subclasses .

      5. If the parent class has a constructor , Subclasses also need construction methods , At this time, you need to overload the constructor of the father in the subclass , And in the construction method parent::__construct () Call the father's constructor , Construct inherited father's member properties . You can also use Class name ::__construct () To invoke the constructor of the parent class , It is not recommended to use . Once the name of the parent class changes , Inheritance fails .

      6. Don't inherit blindly when inheriting code , Humans should not inherit birds . There must be a certain logical relationship .

    • php The difference between inheritance characteristics and inheritance of other languages :

      • php Time order inheritance ( Biological logic ) Language Other languages usually inherit ( Sociological logic , One apprentice has many masters ).
<?php
    // Inheritance features   Grandpa has   Father, too   Father has   Grandpa may not have 
    // Grandpa 
    class GrandFather{
    
    // Member attribute 
    var $familyname = ' Cao ';
    var $lastName = ' fuck ';
    private $xifu = ' The wife ';
    
    // Member method 
    // having dinner 
    function chi {
    
        echo ' Will eat ';
    }
    function he {
    
        echo ' Can drink water ';
    } 
    function __construct{
    
       $this->lastName= ' Tianjiao ';
    }
}
 ''' // Fathers  class Father{ // Member attribute  var $familyname = ' Cao '; var $lastName = ' fuck '; var $money = '100'; // Member method  // having dinner  function chi { echo ' Will eat '; } function he { echo ' Can drink water '; } function piao { echo ' Foot bath members '; } } $father = new Father; var_dump (Father); // But generally, we don't use the way of copying code to inherit '''

     
 // Fathers 
    class Father extends GrandFather{
    
      var $money = '100';
      function piao() {
    
        echo ' Foot bath members ';
    }     
    }
      function __construct{
    
       $this->sex = mt_rand(0,1) ? ' male ':' Woman ';
          //$this->lastName= ' Tianjiao ';
          // Call the father's constructor 
          //GrandFather::__construct
          // Call the father's constructor 2
          
    }
 
$father = new Father;
var_dump (Father);

Access type control

  1. Three encapsulated keywords
    • private Private encapsulation
    • public Public encapsulation
    • protected Protected packaging ( Only when inherited will it be protected )
    • The encapsulation level of methods with the same name of subclasses must Greater than or equal to the parent class Packaging level
    • private -1 protected-2 public-3
    • var Is to encapsulate keywords , But it is not a standard encapsulated keyword , Generally, it is only used for testing and learning .
      • var=%50 public
        • reason :var Only member attributes can be decorated , Member methods cannot be decorated .
keyword / Location Out of class Intra class Subclass
privatexx
public
protectedx
<?php
    class libei {
    
    // Member attribute 
    protected $fname =' Liu ';
    private $lastname = ' To prepare ';
    public $horse = ' Dilu ';
    // Method 
   private function cry(){
    
        echo ' Sobbing, sobbing, sobbing ~';
    }
     protected function say(){
    
         echo ' Talking ';
     }
    public function zhandou(){
    
        echo ' In battle ';
    }
   ''' function texvisit(){ echo $lb->horse; echo '<br/>'; echo $lb->lastname; echo '<br/>'; echo $lb->fname;  The inside of the class can access  }'''
}
// Instantiate a Liu Bei object 
$lb = new luibei();
// Access member properties outside the class 
'''echo $lb->horse; echo '<br/>'; echo $lb->lastname; echo '<br/>'; echo $lb->fname;  Only Lu (public) To access   The rest cannot be accessed  '''
    
'''class adou extends luibei{ function texvisit(){ echo $lb->horse; echo '<br/>'; echo $lb->lastname; echo '<br/>'; echo $lb->fname; }; // Instantiate a Dou object  $ad = new adou; $ad->texvisit();  Lu can   Liu can '''
原网站

版权声明
本文为[hcjtn]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131851350147.html