批改状态:合格
老师批语:
<?php
/*
* 类的继承与方法重载
*
*/
spl_autoload_register(function($className){
require './class/'.$className.'.php';
});
$nut = new Nut('花生','坚果类', 10,false,true);
echo '水果名: '.$nut->name.'<br>';
echo '类型: '.$nut->model.'<br>';
echo '价格: '.$nut->price. '<br>';
echo '能否扦插:'.($nut->qiancha?'能':'不能').'<br>';
echo '是否去壳:'.($nut->guoke?'要':'不用').'<br>';
echo $nut->eat().'<br>';
echo $nut->oils().'<br>';点击 "运行实例" 按钮查看在线实例
<?php
/**
* 创建水果类:Fruit
*/
class Fruit
{
protected $name;
protected $model;
protected $price;
//构造方法
public function __construct($name,$model,$price)
{
$this->name = $name;
$this->model = $model;
$this->price = $price;
}
public function eat()
{
return '休闲食品';
}
}点击 "运行实例" 按钮查看在线实例
<?php
class Nut extends Fruit
{
//创建查询器,实现了外部访问
public function __get($name)
{
return $this->$name;
}
private $qiancha = false;
private $guoke = false;
//必须使用构造方法对使用当前新增属性生效
public function __construct($name,$model,$price,$qiancha,$guoke)
{
parent::__construct($name, $model, $price);
$this->qiancha = $qiancha;
$this->guoke = $guoke;
}
//2.增加新的方法,扩展父类的功能
public function oils()
{
return '能榨油';
}
//3.将父类方法进行重写,就是功能重载,必须使用与父类一样的方法名:call()
public function eat()
{
// return ',能下酒';
//那么,如何在子类中引用父类中的方法呢? 使用关键字: parent,后面跟上双冒号::
return parent::eat().',能下酒';
}
}点击 "运行实例" 按钮查看在线实例

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号