PHP构造方法和析构方法(__construct和__desctruct)

  • 内容
  • 评论
  • 相关

构造方法是在创建对象时自动调用的方法,析构方法是在对象销毁时自动调用的方法。

PHP 构造方法

构造方法常用的场景是在创建对象时用来给变量赋值,构造方法使用__construct定义。

使用示例如下:

<?php
class yourclass{
    public $name;
    public $age;
    function __construct($name,$age){
        $this->name = $name;
        $this->age = $age;
    }
    function get($key){
        return $this->$key;
    }
}
$test_1 = new yourclass('Tom',20);
echo $test_1->get('name');
$test_2 = new yourclass('Jim',30);
echo $test_2->get('age');
?>

执行以上程序的输出结果为:

Tom 30

PHP 析构方法

析构方法和构造方法正好相反,析构方法是在对象被销毁前自动执行的方法。析构方法使用__desctruct定义。

PHP 自带垃圾回收机制,可以自动清除不再使用的对象,释放内存。析构方法在垃圾回收程序执行之前被执行。

使用示例如下:

<?php
class yourclass{
    public $name;
    public $age;
    function __construct($name,$age){
        $this->name = $name;
       $this->age = $age;
    }
    function get($key){
        return $this->$key;
    }
    function __destruct(){
        echo "execute automatically";
    }
}
$test_1 = new yourclass('Tom',20);
echo $test_1->get('name');
echo $test_1->get('age');
?>

执行以上程序的输出结果为:

Tom 20 execute automatically

本文标题:PHP构造方法和析构方法(__construct和__desctruct)

本文地址:http://www.hosteonscn.com/7227.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注