Home  >  Article  >  Backend Development  >  PHP object-oriented-code case sharing of constructor and destructor methods

PHP object-oriented-code case sharing of constructor and destructor methods

黄舟
黄舟Original
2017-03-25 10:12:361679browse

 Construction method and Destruction method are two special methods in object, they are both related to the life cycle of the object . The constructor method is The first method that is automatically called by the object after the object is created. This is the reason why we use the constructor method in the object. The destructor method is the last method that is automatically called by the object before it is destroyed. This is why we use the destructor method in the object. Therefore, the construction method is usually used to complete the initialization work of some objects, and the destructor method is used to complete the cleaning work of some objects before destruction. 1. Constructor method

# In each declared class, there is a special member method called a constructor method. If there is no If you declare it explicitly, there will be a constructor with no parameter list and empty content in the class by default. If you declare it explicitly, the default constructor in the class will not exist. When an object is created, the constructor method will be automatically called once, that is, the constructor method will be automatically called every time the keyword new is used to instantiate the object. The constructor method cannot be actively called through a reference to the object. Therefore, constructors are usually used to perform some useful initialization tasks, such as assigning initial values ​​to member properties when creating objects. In previous versions of PHP5, the method name of the constructor must be the same as the class name. This method can still be used in PHP 5. But in PHP, it is rare to declare a constructor with the same name as the class name. The advantage of this is that the constructor can be independent of the class name. When the class name changes, there is no need to change the corresponding constructor name. For backward compatibility, when creating an object, if there is no constructor named construct() in a class, PHP will search

for a constructor with the same name as the class name and execute it. The format for declaring a constructor in a class is as follows:

function construct( [参数列表] ){ //构造方法名称是以两个下划线开始的
    //方法体,通常用来对成员属性进行初始化赋值}

In PHP, only one constructor can be declared in the same class. The reason is that the constructor method name is fixed, and two functions with the same name cannot be declared in PHP, so there is no constructor method overloading. However, you can use default parameters when declaring the constructor to realize the function of constructor overloading in other

object-oriented

programming languages. In this way, when creating an object, if no parameters are passed in the constructor, default parameters are used to initialize member properties. The constructor can accept parameters and can assign values ​​to object properties when creating an object

  • The constructor can call class methods or other functions

  • The constructor can call the constructor of other classes

  • Constructor usage example:

  • <?phpclass Person{
        private $name;    
        private $age;    
        private $gender;    
        public function construct($name,$age,$gender){
            $this->setName($name);   //调用类方法
            $this->age = $age;        
            $this->setGender($gender);
        }    public function setName($name){
            $this->name = $name;
        }    // ... setter 方法}$person = new Person("yeoman",23,&#39;男&#39;);?>

    Call the parent class constructor, call Constructors of unrelated classes:

    function construct(){
        parent::construct(); // 调用父类的构造函数必须显示的使用parent调用父类构造函数
        classname::construct(); // 调用其他类的构造函数,classname是类名
        //其他操作}

Inheritance

and constructors

The constructor of a subclass in PHP will not actively call the constructor of the parent class. To be displayed, use parent::construct() call:

<?php
class Animal{
    private $name;    
    function construct($name){
        $this->setName($name)        
        echo "动物类被创建!";
    }    // ... 其他方法}class Birds extends Animal{
    private $name;    
    private $leg;    
    function construct($name,$leg){
        parent::construct($name); // 显示调用
        $this->setLeg($leg);       
         echo "鸟类被创建!";
    }    // ... 其他方法}?>
If multi-level inheritance is involved, when parent::construct() is called, it will search upward along the parent class until the most suitable constructor is found. , for example:
// 接上例class Parrot extends Birds{
    private $name;    
    private $leg;    
    private $wing;    
    function construct($name){
        parent::construct($name); 
        // 此时没有找到父类(Birds类)合适的构造函数,只能向上搜索,搜索到Animal类时,才找到合适的构造函数
        echo "鹦鹉类被创建!";        
        $this->smackTalk();        
        /*
        输出结果:
        "动物类被创建!"
        "鹦鹉说话!"
        */
    }    function smackTalk(){
        echo "鹦鹉说话!";    
    }

}

If you want to call the constructors of several parent classes in sequence, you can use the class name to call the constructor directly, for example:

function construct($name,$leg){
       Animal::construct($name); // 调用Animal构造函数
        Birds::construct($name,$leg); // 调用Birds构造函数}

2.

Destructor

The destructor method allows you to perform some specific operations before destroying an object, such as closing the file, releasing the result set, etc. When an object in the heap memory segment loses the reference to access it, it cannot be accessed and becomes a garbage object. Usually the reference to the object is assigned another value or the object loses its reference when the page ends. The destructor is automatically called when the object is destroyed and cannot be called explicitly. The destructor cannot take parameters.

The declaration format of the destructor method is as follows:

function deconstruct(){
    //方法体,通常用来完成一些在对象销毁前的清理任务}

The destructor may be called (but not necessarily) in the following situations:

After the PHP page is loaded;

  • unset() class;

  • Variable
  • refers to another object or value When;
  • PHP's memory recycling mechanism is very similar to JAVA's. Objects without any references are destroyed and recycled using reference counter technology.

  • example:

    <?php
    class test{
        function destruct(){
            echo "当对象销毁时会调用!!!";
        }
    
    }$a = $b = $c = new test();$a = null;unset($b);echo "<hr />";?>

      此例子,如下图,有三个变量引用$a,$b,$c指向test对象,test对象就有3个引用计数,当$a = null时,$a对test对象的引用丢失,计数-1,变为2,当$b被unset()时,$b对test对象的引用也丢失了,计数再-1,变为1,最后页面加载完毕,$c指向test对象的引用自动被释放,此时计数再-1,变为0,test对象已没有变量引用,就会被销毁,此时就会调用析构函数。
    PHP object-oriented-code case sharing of constructor and destructor methods

    在PHP中析构方法并不是很常用,它属于类中可选的一部分,只有需要时才在类中声明。

    <?phpclass Person{
        var $name;    
        var $sex;    
        var $age;    
        function construct($name, $sex, $age){
            $this->name = $name;        
            $this->sex = $sex;       
             $this->age = $age;  
        }    
        function destruct(){
            echo "再见" . $this->name . "<br />";    
        }
    }
    $person1 = new Person("张三三", "男", 23);
    $person1 = null;   //第一个对象将失去引用
    $person2 = new Person("李四四", "女", 17);
    $person3 = new Person("王五五", "男", 43);
    ?>

    运行结果:

    再见张三三
    再见王五五
    再见李四四

      第一个对象在声明完成以后,它的引用就被赋予了空值,所以第一个对象最先失去的引用,不能再被访问了,人后自动调用第一个对象中的析构方法输出“再见张三三”。后面声明的两个对象都是在页面执行结束时失去的引用,也都自动调用了析构方法。但因为对象的引用都是放在栈内存中的,由于栈的后进先出特点,最后创建的对象会被最先释放,多以先自动调用第三个对象的析构方法,最后才调用第二个对象的析构方法。

The above is the detailed content of PHP object-oriented-code case sharing of constructor and destructor methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn