0

我对 PHP5 的 OOP 风格很陌生,我注意到在示例类和生产类中__construct__deconstruct

我已阅读此手册:

http://php.net/manual/en/language.oop5.decon.php

并查看了 StackOverflow 上的一系列问题/答案。我仍然无法理解它存在的实际含义是什么?

class foo {
   function __construct()
   {
     // do something 
   }

   public function Example ()
   {
    echo "Example Functions";
   }

   function __destruct()
   {
     // do something
   }
}

同一个类可以在没有命中的情况下发挥相同的作用:

class foo {
       public function Example ()
       {
        echo "Example Functions";
       }
    }

但是上面的例子中的手册指出,我的第一个函数将作为__construct

为什么这是 PHP5 OOP 类中的优先事项?

4

3 回答 3

1

__解构

当一个类即将被垃圾收集时调用析构函数,它允许您在释放类之前执行最后一分钟的操作。

_constructor 只是对立面。它允许您在对象创建期间为其设置属性。

这是创建构造函数的旧方法,根据文档,它留在那里是为了向后兼容。

public function Example ()
{
  echo "Example Functions";
}

“为了向后兼容,如果 PHP 5 找不到给定类的 __construct() 函数,并且该类没有从父类继承一个,它将按类的名称搜索旧式构造函数。实际上,这意味着唯一会出现兼容性问题的情况是该类有一个名为 __construct() 的方法,该方法用于不同的语义。”

http://php.net/manual/en/language.oop5.decon.php

于 2013-03-29T01:38:48.543 回答
1
class Foo {
    public function __construct() {
        print("This is called when a new object is created");
        // Good to use when you need to set initial values,
        // (possibly) create a connection to a database or such.
    }

    public function __destruct() {
        print("This is called when the class is removed from memory.");
        // Should be used to clean up after yourself, close connections and such.
    }
}

$foo = new Foo();

添加,

class Person {

    private $name; // Instance variable
    private $status; // Instance variable

    // This will be called when a new instance of this class i created (constructed)
    public function __construct($name, $age) {
        $this->name = ucfirst($name); // Change input to first letter uppercase.

        // Let the user of our class input something he is familiar with,
        // then let the constructor take care of that data in order to fit
        // our specific needs.
        if ($age < 20) {
            $this->status = 'Young';
        } else {
            $this->status = 'Old';
        }
    }

    public function printName() {
        print($this->name);
    }

    public function printStatus() {
        print($this->status);
    }
}

$Alice = new Person('alice', 27);
$Alice->printName();
$Alice->printStatus();

/添加

如果您运行上述代码并阅读注释,您应该能够理解何时以及如何使用构造函数和析构函数。

于 2013-03-29T01:41:49.023 回答
0

您需要意识到一个类定义了一个类型,这意味着一种数据以及可以对该数据执行的操作。该数据在内部存储为成员变量。同样,这些操作由类的方法定义。构造函数用于初始化对象的初始内部状态(即其成员变量和任何内部操作)。

PHP 中的析构函数通常用于手动对象清理。由于 PHP 的“即发即弃”特性,它们并不经常使用。它们可用于在长时间运行的脚本中释放资源(数据库连接、文件句柄)。

于 2013-03-29T01:49:23.930 回答