3、php构造函数、析构函数

构造函数__construct() 析构函数__destruct()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
class Person{
public $username='king';
public $age=12;
public $email='382771946@qq.com';
public $sex='男';
//构造函数,当创建对象的时候首先会调用构造函数,适合初始化数据操作
public function __construct($username,$age,$email,$sex){
echo '当新建对象的时候我首先会被调用<br/>';
$this->username=$username;
$this->age=$age;
$this->sex=$sex;
$this->email=$email;
}
//析构函数,不能带有参数,析构函数会在对象的所有引用被删除或显示的销毁之前会被调用
//可以通过析构函数释放资源、释放结果集
public function __destruct(){
echo 'say Goodbye to '.$this->username.'<br/>';
}
//成员方法
public function eat(){
echo 'eat...<br/>';
}
public function sleep(){
echo 'sleep...<br/>';
}
public function play(){
echo 'play...<br/>';
}
public function personInfo(){
echo '用户名为:'.$this->username.'<br/>';
echo '年龄:'.$this->age.'<br/>';
echo '性别:'.$this->sex.'<br/>';
echo '邮箱:'.$this->email.'<br/>';
}
}
// $p1=new Person;
// var_dump($p1);
// echo '<hr/>';
// $p2=new Person;
// $p2->username='queen';
// $p2->age=32;
// $p2->email='maizi@qq.com';
// $p2->sex='女';
// var_dump($p2);
$p1=new Person('king',12,'382771946@qq.com','男');
// var_dump($p1);
$p1->personInfo();
// $p1=null;
unset($p1);
echo '销毁对象<br/>';
$p2=new Person('queen',32,'queen@qq.com','女');
$p2->personInfo();