📜  PHP |构造函数和析构函数

📅  最后修改于: 2022-05-13 01:57:39.907000             🧑  作者: Mango

PHP |构造函数和析构函数

构造函数是特殊的成员函数,用于对类中新创建的对象实例进行初始设置,这是PHP5 中面向对象概念的关键部分。
构造函数是定义未来对象及其性质的非常基本的构建块。您可以说构造函数是对象创建的蓝图,为成员函数和成员变量提供值。
一旦对象被初始化,构造函数就会被自动调用。析构函数用于销毁对象并在执行结束时自动调用。
在本文中,我们将学习构造函数和析构函数的面向对象概念。
两者都是具有不同概念但名称相同的任何类的特殊成员函数,但析构函数前面有一个~ Tilda运算符
句法:

  • __构造():
function __construct()
       {
       // initialize the object and its properties by assigning 
       //values
       }

  • __destruct():
function __destruct() 
       {
       // destroying the object or clean up resources here 
       }

注意:构造函数定义在类的公共部分。甚至类的属性值也是由构造函数设置的。
构造函数类型:

  • 默认构造函数:它没有参数,但可以动态传递给默认构造函数的值。
  • 参数化构造函数:它接受参数,您也可以将不同的值传递给数据成员。
  • 复制构造函数:它接受其他对象的地址作为参数。

继承:由于继承是一个面向对象的概念,构造函数从父类继承到从它派生的子类。每当子类有自己的构造函数和析构函数时,它们就会按优先级或优先顺序调用。
预定义的默认构造函数:通过使用 __construct()函数,您可以定义一个构造函数。
注意:如果Pre-defined Constructor(__construct)和自定义构造函数在同一个类中,Pre-defined Constructor变成Constructor,自定义构造函数变成普通方法。
程序:

php


php
name=$name;
        $this->profile=$position;
 
 
    }    
    function show_details()
    {
        echo $this->name." : ";
        echo "Your position is ".$this->profile."\n";
    }
}
     
$employee_obj= new Employee("Rakesh","developer");
$employee_obj->show_details();
     
$employee2= new Employee("Vikas","Manager");
$employee2->show_details();
 
?>


php


php
name = "Class object! ";
        }
 
        function __destruct()
        {
            echo "destroying " . $this->name . "\n";
        }
    }
$obj = new Someclass();
 
?>


输出:



Its a Pre-defined Constructor of the class Tree

参数化构造函数:类的构造函数接受参数或参数。
->运算符用于设置变量的值。在构造函数方法中,您可以在对象创建期间为变量赋值。
程序:

PHP

name=$name;
        $this->profile=$position;
 
 
    }    
    function show_details()
    {
        echo $this->name." : ";
        echo "Your position is ".$this->profile."\n";
    }
}
     
$employee_obj= new Employee("Rakesh","developer");
$employee_obj->show_details();
     
$employee2= new Employee("Vikas","Manager");
$employee2->show_details();
 
?>

输出:

Rakesh : Your position is developer
Vikas : Your position is Manager

构造函数以两个下划线开头,通常看起来像普通的PHP函数。有时这些构造函数被称为魔术函数,以两个下划线开头,并具有比普通方法更多的功能。创建包含构造函数的某个类的对象后,构造函数的内容将自动执行。
注意:如果PHP类有构造函数,那么在创建对象时,会调用该类的构造函数。构造函数没有返回类型,所以它们不返回任何不为空的东西。
使用构造函数的优点:

  • 构造函数提供了传递参数的能力,这些参数有助于在创建期间成员变量的自动初始化。
  • 构造函数可以根据需要具有任意数量的参数,并且可以使用默认参数定义它们。
  • 它们鼓励可重用性,避免在创建类的实例时重新初始化。
  • 您可以在构造函数方法中启动会话,这样您就不必每次都启动所有函数。
  • 它们可以调用类成员方法和函数。
  • 他们甚至可以从 Parent 类调用其他构造函数。

注意: __construct() 方法始终具有公共可见性因素。
程序:

PHP


输出

Parent class constructor.
Parent class constructor.
Child Class constructor

注意:每当创建子类对象时,都会自动调用子类的构造函数。
构函数析构函数也是一个特殊的成员函数,它与构造函数方法完全相反,在类的实例从内存中删除时调用。析构函数 (__destruct (void): void) 是在没有对类的任何对象的引用或超出范围或即将显式释放时调用的方法。
它们没有任何类型或返回值。它只是在为对象取消分配内存之前或在PHP脚本执行完成期间或执行控制离开块时调用。
当完整的脚本或代码终止时,全局对象将被销毁。只要代码中不再需要资源,就会在析构函数方法中在内存释放或关闭文件之前清理资源。类对象的自动销毁由PHP垃圾收集器处理。

~ ClassName()
{

}

注意:当PHP代码使用PHP exit()die() 函数在最后一行完全执行时,会调用析构函数方法。

程序:

PHP

name = "Class object! ";
        }
 
        function __destruct()
        {
            echo "destroying " . $this->name . "\n";
        }
    }
$obj = new Someclass();
 
?>

输出:

In constructor, destroying Class object! 

注意:在继承的情况下,如果子类和父类都有析构函数,则先调用派生类的析构函数,再调用父类的析构函数。

析构函数的优点:

  • 析构函数为对象提供了释放内存分配的机会,以便为新对象提供足够的空间或为其他任务释放资源。
  • 它有效地使程序运行更有效,并且在执行清理任务时非常有用。

__constructors 和 __destructors 的比较:

ConstructorsDestructors
Accepts one or more arguments.No arguments are passed. Its void.
function name is _construct().function name is _destruct()
It has same name as the class.It has same name as the class with prefix ~tilda.
Constructor is involved automatically when the object is created.Destructor is involved automatically when the object is destroyed.
Used to initialize the instance of a class.Used to de-initialize objects already existing to free up memory for new accommodation.
Used to initialize data members of class.Used to make the object perform some task before it is destroyed.
Constructors can be overloaded.Destructors cannot be overloaded.
It is called each time a class is instantiated or object is created.It is called automatically at the time of object deletion .
Allocates memory.It deallocates memory.
Multiple constructors can exist in a class.Only one Destructor can exist in a class.
If there is a derived class inheriting from base class and the object of the derived class is created, 
the constructor of base class is created and then the constructor of the derived class.
The destructor of the derived class is called and then the destructor of base class just the reverse order of 
constructor.
The concept of copy constructor is allowed where an object is initialized from the address of another object . 
 
No such concept is allowed.

结论:在真实的编程世界中,构造函数和析构函数方法非常有用,因为它们使编码过程中非常关键的任务变得更容易。这些鼓励代码的可重用性,而无需不必要的重复。它们都被编译器隐式调用,即使它们没有在类中定义。