PHP构造函数和析构函数

十多年不搞php了,概念有点模糊,写了一个类居然把__construt写成__constructor,问题看了半天。

对应构造函数和析构函数,写程序验证析构函数的确是会被销毁。

<?php

$root = $_SERVER['DOCUMENT_ROOT'];

$path = $root . '/hello.txt';
$hello = new Hello($path);
$hello->write('aaa');
$hello->write('bbb');
$hello->write('ccc');
echo ($path);

class Hello
{
    private $f = false;
    function __construct($path)
    {
        $this->f = fopen($path, 'w');
        $this->write('*begin*');
    }
    function __destruct()
    {
        $this->write('*end*');
        if ($this->f) {
            fclose($this->f);
        }
    }
    public function write($something)
    {
        if ($this->f) {
            fwrite($this->f, $something . "\n");
        }
    }
}

生成的hello.txt内容如下:

*begin*
aaa
bbb
ccc
*end*

评论

暂无评论