批改状态:未批改
老师批语:
父类:
<?php
class Mp3
{
protected $brand;
protected $price;
protected $capacity;
public function __construct($brand, $price, $capacity)
{
$this->brand = $brand;
$this->price = $price;
$this->capacity = $capacity;
}
public function play()
{
return '播放音乐';
}
}点击 "运行实例" 按钮查看在线实例
子类:
<?php
class Mp4 extends Mp3
{
public function __get($name)
{
return $this->$name;
}
private $music = false;
private $internet = false;
public function __construct($brand, $price, $capacity, $music, $internet)
{
parent::__construct($brand, $price, $capacity);
$this->music = $music;
$this->internet = $internet;
}
public function video()
{
return '播放视频';
}
public function play()
{
return parent::play().',同时还能录音';
}
}点击 "运行实例" 按钮查看在线实例
案例:
<?php
spl_autoload_register(function ($className){
$path = __DIR__.'/class/'.$className.'.php';
if (file_exists($path) && is_file($path)) {
require $path;
}
});
$mp4 = new Mp4('sony',1888,'16G',true,true);
echo '品牌: '.$mp4->brand.'<br>';
echo '价格: '.$mp4->price.'<br>';
echo '容量: '.$mp4->capacity.'<br>';
echo '是否支持播放音乐: '.($mp4->music ? '支持' : '不支持').'<br>';
echo '是否支持上网: '.($mp4->internet ? '支持' : '不支持').'<br>';
echo $mp4->play().'<br>';
echo $mp4->video().'<br>';点击 "运行实例" 按钮查看在线实例
效果图:

总结:
子类继承用extends
public: 在外部、内部、子类中都可以用
private: 仅限于类内部使用
protected: 在本类和子类中使用
类的自动加载:
spl_autoload_register(function ($className){
str_replace('\\','/',$className);
$path = __DIR__.'/class/'.$className.'.php';
if (file_exists($path) && is_file($path)) {
require $path;
}
});点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号