Php 简明教程

PHP – Constructor and Destructor

与大多数面向对象语言一样,您还可以在 PHP 中的类中定义一个构造函数。当您使用 new 运算符声明一个对象时,它的成员变量不会分配任何值。构造函数用于在声明时初始化每个新对象。PHP 还支持具有析构函数,该析构函数会从内存中销毁对象,因为它不再有任何引用。

As in most of the object-oriented languages, you can define a constructor function in a class in PHP also. When you declare an object with the new operator, its member variables are not assigned any value. The constructor function is used to initialize every new object at the time of declaration. PHP also supports having a destructor function that destroys the object from the memory as it no longer has any reference.

The __construct() Function

PHP 提供了一个用于初始化对象的 __construct() 函数。

PHP provides a __construct() function that initializes an object.

__construct(mixed ...$values = ""): void

类内部的构造函数方法在每个新创建的对象上自动调用。请注意,定义构造函数不是强制性的。但是,如果存在,它适用于在使用对象之前它可能需要的任何初始化。

The constructor method inside a class is called automatically on each newly created object. Note that defining a constructor is not mandatory. However, if present, it is suitable for any initialization that the object may need before it is used.

您可以向构造函数传递任意多个参数。__construct() 函数没有任何返回值。

You can pass as many as arguments you like into the constructor function. The __construct() function doesn’t have any return value.

让我们在前一章中使用的 Book 类中定义一个构造函数

Let us define a constructor in the Book class used in the previous chapter

<?php
   class Book {

      /* Member variables */
      var $price;
      var $title;

      /*Constructor*/
      function __construct(){
         $this->title = "PHP Fundamentals";
         $this->price = 275;
      }

      /* Member functions */
      function getPrice() {
         echo "Price: $this->price \n";
      }

      function getTitle(){
         echo "Title: $this->title \n";
      }
   }

   $b1 = new Book;
   $b1->getTitle();
   $b1->getPrice();
?>

它将生成以下 output

It will produce the following output

Title: PHP Fundamentals
Price: 275

Parameterized Constructor

$b1 的成员变量已经初始化,而无需调用 setTitle()setPrice() 方法,因为构造函数在对象声明后立即被调用。但是,此构造函数将针对每个对象调用,因此每个对象都具有 titleprice 属性的相同值。

The member variables of $b1 have been initialized without having to call setTitle() and setPrice() methods, because the constructor was called as soon as the object was declared. However, this constructor will be called for each object, and hence each object has the same values of title and price properties.

要使用不同的值初始化每个对象,请使用带参数定义 @{s1} 函数。

To initialize each object with different values, define the __construct() function with parameters.

@{s2} 函数的定义更改为以下内容 −

Change the definition of __construct() function to the following −

function __construct($param1, $param2) {
   $this->title = $param1;
   $this->price = $param2;
}

要初始化对象,请在声明中将值传递给括号内的参数。

To initialize the object, pass values to the parameters inside a parenthesis in the declaration.

$b1 = new Book("PHP Fundamentals", 375);

Example

现在,每个对象都可以对成员变量具有不同的值。

Now, you can have each object with different values to the member variables.

<?php
   class Book {

      /* Member variables */
      var $price;
      var $title;

      /*Constructor*/
      function __construct($param1, $param2) {
         $this->title = $param1;
         $this->price = $param2;
      }

      /* Member functions */
      function getPrice(){
         echo "Price: $this->price \n";
      }

      function getTitle(){
         echo "Title: $this->title \n";
      }
   }

   $b1 = new Book("PHP Fundamentals", 375);
   $b2 = new Book("PHP Programming", 450);

   $b1->getTitle();
   $b1->getPrice();
   $b2->getTitle();
   $b2->getPrice();
?>

它将生成以下 output

It will produce the following output

Title: PHP Fundamentals
Price: 375
Title: PHP Programming
Price: 450

Constructor Overloading

方法重载是面向对象编程中的一个重要概念,其中一个类可能具有多个构造函数定义,每个定义具有不同的参数数量。然而,PHP 不支持方法重载。可以通过在构造函数中使用带默认值的参数来克服此限制。

Method overloading is an important concept in object-oriented programming, where a class may have more than one definitions of constructor, each having different number of arguments. However, PHP doesn’t support method overloading. This limitation may be overcome by using arguments with default values in the constructor function.

将 __construct() 函数更改为以下内容:

Change the __construct() function to the following −

function __construct($param1="PHP Basics", $param2=380) {
   $this->title = $param1;
   $this->price = $param2;
}

现在,声明一个不带参数的对象,而另一个带参数。不带参数的对象将用默认参数初始化,带参数的对象将用传递的值初始化。

Now, declare an object without passing parameters, and the other with parameters. One without parameters will be initialized with default arguments, the other with the values passed.

$b1 = new Book();
$b2 = new Book("PHP Programming", 450);

它将生成以下 output

It will produce the following output

Title: PHP Basics
Price: 380
Title: PHP Programming
Price: 450

Type Declaration in Constructor

由于 PHP(7.0 及更高版本)允许对函数参数使用标量类型声明,因此可以将 __construct() 函数定义为:

Since PHP (version 7.0 onwards) allows scalar type declarations for function arguments, the __construct() function may be defined as −

function __construct(string $param1="PHP Basics", int $param2=380) {
   $this->title = $param1;
   $this->price = $param2;
}

在 PHP 的早期版本中,允许使用类的名称来定义构造函数,但此功能自 PHP 8.0 起已弃用。

In the earlier versions of PHP, using the name of class to define a constructor function was allowed, but this feature has been deprecated since PHP version 8.0.

The __destruct() Function

PHP 还有一个 __destructor() 函数。它实现了一个析构函数概念,与其他面向对象语言(如 C++)中的概念类似。只要不存在对特定对象的引用,就会调用析构函数方法。

PHP also has a __destructor() function. It implements a destructor concept similar to that of other object-oriented languages, as in C++. The destructor method will be called as soon as there are no other references to a particular object.

__destruct(): void

_destruct() 函数没有任何参数,也没有任何返回值。_destruct() 函数在任何对象超出作用域时都会自动调用这一事实可以通过在函数中放置 var_dump($this) 来验证。

The _destruct() function doesn’t have any parameters, neither does it have any return value. The fact that the _destruct() function is automatically called when any object goes out of scope, can be verified by putting var_dump($this) inside the function.

如上所述, $this 携带对调用对象的引用;转储显示,成员变量被设置为 NULL

As mentioned above, $this carries the reference to the calling object, the dump shows that the member variables are set to NULL

在 Book 类中添加析构函数,如下所示:

Add destructor function in the Book class as follows −

function __destruct() {
   var_dump($this);
   echo "object destroyed";
}

当程序退出时,将显示以下 output

As the program exits, the following output will be displayed −

object(Book)#1 (2) {
   ["price"]=>
   NULL
   ["title"]=>
   NULL
}
object destroyed