<?php /** * 类的继承与访问控制 * 类的继承:extends * 类的访问控制:public private protected */ header('Content-Type:text/html;charset=utf-8'); //创建一个父类 class Books { protected $name; //在子类中可以访问,在外部不可访问 private $price; //仅在本类内部可访问,在子类和外部均不可访问,可通过创建外部接口来实现在被外部访问 public $num; public function __construct($name='《卧底经济学》',$price=48) //创建构造方法,来初始化属性name和price { $this->name = $name; $this->price = $price; } public function Cont($num=1) //创建Cont方法来执行总价计算操作 { $this->num = $num; $this->totalPrice = $this->price*$this->num; return ($this->name).($this->num).'本,共'.$this->totalPrice.'元'; } //创建一个外部接口来在外部访问私有属性$price public function Price() { return $this->price; } //创建一个外部接口来在外部访问被保护的属性$name public function Name() { return $this->name; } } echo (new Books('《魔鬼经济学》','30'))->Cont(3); echo '<hr>'; echo (new Books('《魔鬼经济学》','30'))->Price(); echo '<hr>'; //创建一个子类 class Fiction extends Books { public $ilike; public function Ilike($ilike='《见识》') { $this->ilike = $ilike; echo '我喜欢的书有:'.$this->ilike; echo (new Books())->name; } } echo (new Fiction())->Ilike(); echo '<hr>'; echo (new Fiction('《鬼吹灯》','42'))->Cont(3); echo '<hr>'; echo (new Fiction())->Name(); echo '<hr>'; echo (new Fiction())->Price();