摘要:本章主要学习了类的继承,以及如何使用范围解析符,并学习了使用static关键字定义静态成员和静态类,通过static关键字实现后期静态绑定,最后学习了类的属性和方法的重载。通过学习,对本章进行练习,代码如下:主调用页面:chapter4-2.php<?php //自动加载类 spl_autoload_register(function ($className){ &n
本章主要学习了类的继承,以及如何使用范围解析符,并学习了使用static关键字定义静态成员和静态类,通过static关键字实现后期静态绑定,最后学习了类的属性和方法的重载。通过学习,对本章进行练习,代码如下:
主调用页面:chapter4-2.php
<?php
//自动加载类
spl_autoload_register(function ($className){
require $className . '.php';
});
//使用管理员访问
echoApple('admin');
echo '<hr>';
//使用普通用户访问
echoApple('zhangs');
function echoApple($userID)
{
$apple=new Apple('日本进口苹果','苹果',15.00);
echo '店名:',$apple->getDianMing(), ',品牌:',$apple->brand,',名称:',$apple->name,',价格:',$apple->getPrice(),',采购价:',$apple->getInPrice($userID),',老板:',Apple::getBossName($userID),',标语:',Apple::getBiaoYu();
echo '<br>通过方法重载获取位置:',$apple->getShow('金新北路','汕头市');
}Fruit.php
<?php
class Fruit
{
public $brand='特产水果';
public $name='水果';
protected $price=10.00;
private $inPrice;
const DIANMING='百果园';
protected static $bossName='1Pong';
protected static $biaoYu='多吃水果';
public function __construct($brand,$name,$price)
{
$this->brand=$brand;
$this->name=$name;
$this->price=$price;
}
//获取进货价
public function getInPrice($userID)
{
$reValue='';
if(strtolower($userID)==='admin')
{
$reValue=$this->price * 0.3 . '';
}
else
{
$reValue='保密';
}
return $reValue;
}
//获取老板名称
public static function getBossName($userID)
{
$reValue='';
if(strtolower($userID)==='admin')
{
$reValue= static::$bossName;
}
else
{
$reValue='保密';
}
return $reValue;
}
//获取商品单价
public function getPrice()
{
return $this->price;
}
//获取宣传标语
public static function getBiaoYu()
{
return static::$biaoYu;
}
}Apple.php
<?php
require 'HelpClass.php';
class Apple extends Fruit
{
public $brand='新疆大苹果';
public $name='苹果';
protected $price=5.00;
protected static $biaoYu='an apple a day keep the doctor away';
public function __construct($brand, $name, $price)
{
parent::__construct($brand, $name, $price);
}
//获取店名
public function getDianMing()
{
return parent::DIANMING;
}
//通过重载获取HelpClass的getShow方法
public function __Call($method,$arguments)
{
return call_user_func_array([(new HelpClass),'getShow'],$arguments);
}
}HelpClass.php
<?php
class HelpClass
{
//获取位置
public function getShow($arguments)
{
$place=func_get_arg(0);
$city=func_get_arg(1);
return $city.$place;
}
}执行效果图:

批改老师:查无此人批改时间:2018-12-07 14:26:26
老师总结:做的不错,连保密都考虑到了。你适合做程序员,加油。