1,__construct在对象开始初始化时调用,__destruct在对象销毁的时候调用;
2,成员函数和属性在默认情况下是public,public可以不用写;public定义的属性和成员函数,对象可以直接访问,内部的成员函数也可以访问;protect定义的成员函数和属性,只有成员函数和子类的成员函数可以访问,对象不可以直接访问;
private定义的属性和成员函数,只有本类的成员函数可以访问,对象不可以直接访问,子类的成员函数也不可以访问;
<?php
class animal
{
public $head;
private $height;
protected $width;
function __construct($height,$width)//属性和成员函数默认是public形式,所以public可以不用写
{
$this->height=$height;
$this->width=$width;
echo '<br>我是构造函数的输出<br>';
}
public function move()
{
echo '<br>我是move方法的执行结果!<br>';
}
function introduce()
{
echo '<br>我的高度是:'.$this->height;
echo '<br>我的宽度是:'.$this->width;
}
function __destruct()
{
echo '现在对象以及运行完,开始销毁了!';
}
}
$animal_obj=new animal('120','30');
//$animal_obj->height=50; 此行会报错,因为对象不能访问private私有成员变量;
$animal_obj->head='big';
//$animal_obj->width=72; 此行会报错,因为对象不能访问protected受保护成员变量;
$animal_obj->introduce();
$animal_obj->move();
?>