<?php class car { //属性 private $brand; private $type; private $color; private $size=[]; //构造方法 public function __construct($brand='',$type='',$color='',array $size=[]) { $this->brand = $brand; $this->type = $type; $this->color = $color; $this->size = $size; } //__get魔术方法 查询器 public function __get($property_name) { $msg = null; if (isset($this->$property_name)){ $msg = $this->$property_name; } else { $msg = '属性'.$property_name.'不存在!'; } return $msg; } //设置器 public function __set($property_name,$value) { $this->$property_name = $value; } //方法 public function starting() { return '汽车启动!'; } public function drive() { return '汽车驾驶!'; } } ?>
点击 "运行实例" 按钮查看在线实例
<?php /** * */ class car_bm extends car { private $ccs = true; private $gps = true; function __construct($brand='',$type='',$color='',array $size=[],$ccs,$gps) { // parent::__construct($brand='',$type='',$color='',array $size=[]); parent::__construct($brand,$type,$color,$size); // 属性扩展 $this->$ccs = $ccs; $this->gps = $gps; } public function starting() { return '远程遥控启动!'; } public function drive() { return parent::drive().'还支持无人驾驶!'; } } ?>
点击 "运行实例" 按钮查看在线实例
<?php //类自动加载 spl_autoload_register(function($className){ require './class/'.$className.'.php'; }); $bm_car = new car_bm('宝马','X5','白色',[4909,1938,1772],true,true); echo '品牌:'.$bm_car->brand.'<br>'; echo '型号:'.$bm_car->type.'<br>'; echo '颜色:'.$bm_car->color.'<br>'; echo '尺寸: '. print_r($bm_car->size,true). '<br>'; //子类扩展属性 echo '定速巡航:'.($bm_car->ccs?'支持':'无'). '<br>'; echo 'GPS导航:'.($bm_car->gps?'支持':'无'). '<br>'; //子类扩展方法 echo '<hr>'; echo $bm_car->starting(). '<br>'; echo $bm_car->drive(). '<br>'; ?>
点击 "运行实例" 按钮查看在线实例