PHP Velho Oeste 2024

构造函数

构造函数是类中的一个特殊函数,当使用 new 操作符创建一个类的实例时,构造函数将会自动调用。当函数与类同名时,这个函数将成为构造函数。如果一个类没有构造函数,则调用基类的构造函数,如果有的话。

<?php
class Auto_Cart extends Cart {
    function 
Auto_Cart() {
        
$this->add_item ("10"1);
    }
}
?>

上文定义了一个 Auto_Cart 类,即 Cart 类加上一个构造函数,当每次使用“new”创建一个新的 Auto_Cart 类实例时,构造函数将自动调用并将一件商品的数目初始化为“10”。构造函数可以使用参数,而且这些参数可以是可选的,它们可以使构造函数更加有用。为了依然可以不带参数地使用类,所有构造函数的参数应该提供默认值,使其可选。

<?php
class Constructor_Cart extends Cart {
    function 
Constructor_Cart($item "10"$num 1) {
        
$this->add_item ($item$num);
    }
}

// 买些同样的无聊老货
$default_cart = new Constructor_Cart;
// 买些实在货...
$different_cart = new Constructor_Cart("20"17);
?>

也可以使用 @ 操作符来抑制发生在构造函数中的错误。例如 @new

<?php
class A
{
    function 
A()
    {
      echo 
"I am the constructor of A.<br>\n";
    }

    function 
B()
    {
        echo 
"I am a regular function named B in class A.<br>\n";
        echo 
"I am not a constructor in A.<br>\n";
    }
}

class 
extends A
{
    function 
C()
    {
        echo 
"I am a regular function.<br>\n";
    }
}

// 调用 B() 作为构造函数
$b = new B;
?>

类 A 中的函数 B() 将立即成为类 B 中的构造函数,虽然并不是有意如此。PHP 4 并不关心函数是否在类 B 中定义的,或者是否被继承来的。

Caution

PHP 4 不会从派生类的构造函数中自动调用基类的构造函数。恰当地逐次调用上一级的构造函数是用户的责任。

析构函数是一种当对象被销毁时,无论使用了 unset() 或者简单的脱离范围,都会被自动调用的函数。PHP 中没有析构函数。可以用 register_shutdown_function() 来替代模拟大多数析构函数的效果。

add a note add a note

User Contributed Notes 2 notes

up
0
Anonymous
9 years ago
I only just noticed this page is specifically referring to PHP 4, so I'd suggest changing
"There are no destructors in PHP."
to
"There are no destructors in PHP 4. Support for destructors was added in PHP 5."
up
0
Anonymous
9 years ago
"There are no destructors in PHP. You may use register_shutdown_function() instead to simulate most effects of destructors. "

I thought this was a particularly strange statement, seeing as that I use __construct() en __destruct() the whole time. And surely, from http://php.net/manual/en/language.oop5.decon.php we can read this:

"void __destruct ( void )
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence. "

And even:
"The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing."

So PHP definitely supports destructors.
To Top