构造方法

构造方法是类在刚声明的时候被执行。

格式:[修饰符] function __construct(参数){
程序体
}

析构方法

没有有关这个类调用的时候执行。

格式:[修饰符] function __destruct(参数){
程序体
}

使用


  1. <?php
  2. class Person
  3. {
  4. public function __construct($name, $age)
  5. {
  6. // 当这个类被new的时候自动执行
  7. echo "hello {$name} {$age}";
  8. echo "<br>";
  9. $this->name= $name;
  10. $this->age = $age;
  11. }
  12. public function data()
  13. {
  14. return $this->age;
  15. }
  16. public function __destruct()
  17. {
  18. // 用途可以进行资源的释放 数据库关闭 读取文件关闭
  19. // 对象被销毁的时候执行 没有代码再去运行了
  20. echo "bye bye {$this->name}";
  21. echo "<hr>";
  22. }
  23. }
  24. new Person("xiaowang", 30);
  25. new Person("小红", 20);

上面代码会先输出 hello xiaowang 30 , bey bey xiaowang。然后再输出 hello 小红 20, bey bey 小红。所以可以看出,每次new的时候都会执行一遍构造函数 和 析构函数。但是析构函数是在类的方法没有在被调用的时候才会触发。