批改状态:未批改
老师批语:
父类Computer.php:
<?php
/**
* 创建基类,父类:电脑类
*/
class Computer
{
//使用范围
// public : 在外部,内部,子类都可以用====公共的
// private : 只能在类内部使用 === 私有的
// protected :类内部、子类可用 === 受保护的
protected $brand;
protected $model;
protected $price;
//构造方法
public function __construct($brand='',$model='',$price='')
{
$brand ? ($this->brand = $brand) : $this->brand;
$model ? ($this->model = $model) : $this->model;
$price ? ($this->price = $price) : $this->price;
}
public function internet()
{
return '网上冲浪';
}
}点击 "运行实例" 按钮查看在线实例
子类:Hp_notebook.php
<?php
/**
* 继承关键字 : extends
* HP_notebook:惠普笔记本电脑
* HP_notebook继承至Computer
* Computer:父类
* HP_notebook:子类
* 子类可以继承父类中的所有受保护的或公共成员
*
* 子类中的用途:扩展父类中的属性或者功能(方法进行重载,重写)
*/
class HP_notebook extends Computer
{
//1.对父类的属性进行扩展,增加新的特征,全部设置为private
private $color = '黑色';
private $size = '15英寸';
//构造方法
public function __construct($brand = '', $model = '', $price = '',$color='',$size='')
{
//父类构造器中的属性初始化
parent::__construct($brand, $model, $price);
//子类构造器中的属性初始化
$color ? ($this->color = $color) : $this->color;
$size ? ($this->size = $size) : $this->size;
}
//获取器
public function __get($name)
{
return $this->$name;
}
//增加新功能。方法
public function game()
{
return '玩游戏';
}
//类方法的重写,重载,覆盖,(函数名一样);;;更多时候是需要把父类中进行功能扩展
public function internet()
{
return parent::internet().',,,,,好玩啊';
}
}点击 "运行实例" 按钮查看在线实例
php文件:demo2:
<?php
/**
* 类的继承与方法加载类
*/
require '../UTF/UTF-8.php';
spl_autoload_register(function($className){
$path = __DIR__.'/class/'.$className.'.php';
if(file_exists($path) && is_file($path)){
require $path;
}
});
$hp_notebook = new HP_notebook('惠普','ENVY','5300','白色','10英寸');
echo $hp_notebook->brand."<br>";
echo $hp_notebook->model."<br>";
echo $hp_notebook->price."元<br>";
echo $hp_notebook->color."<br>";
echo $hp_notebook->size."<br>";
echo $hp_notebook->Internet()."<br>";
echo $hp_notebook->game();点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号