构造方法 析构函数
$one =new One('heihei','30','28');
$one->hello();
class One{
public $name='cc';
public $age='18';
public $number='23';
//构造函数 在对象被实例化时自动调用该方法
function __construct($name,$age,$number){
//$this是php的伪变量 表示对象本身 可以通过$this->属性/方法 调用
$this->name=$name;
$this->age=$age;
$this->number=$number;
echo 'construct '.$this->name.' '.$this->age.' '.$this->number.'<br>';
}
public function hello(){
echo 'hello world<br>';
}
public function run(){
echo 'this is run method';
}
//在程序执行结束的时候自动调用 用来释放资源
function __destruct(){
echo 'this is destruct '.$this->name.'<br>';
}
}
继承+访问控制
$nba=new NbaPlayer('rain','190','180');
$nba->eat('kfc');
echo $nba->team;
echo $nba->getAge();
class Human{
public $name;
protected $height;//只有自身和子类可以访问
public $weight;
private $isHungry=true;
public function eat($food){
echo $this->name.' eating '.$food.'<br>';
}
}
//PHP单继承
class NbaPlayer extends Human{
//定义属性
public $playNum='23';
public $team='Bull';
//私有成员 只能在类内部访问
private $age='30';
public function getAge(){
return $this->age;
}
public function __construct($name,$height,$weight){
$this->name=$name;
$this->height=$height;
$this->weight=$weight;
}
}