search
HomeBackend DevelopmentPHP TutorialPHP object-oriented-code case sharing of constructor and destructor methods

 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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.