本章主要学习了trait特性的使用,以及命名空间的导入和引用。通过学习,在上一章的练习的基础上,继续增加了命名空间的声明和导入,并练习了trait的引用。代码如下:
主页面:chapter4-3.php
<?php //自动加载类 spl_autoload_register(function ($className){ require $className . '.php'; }); require 'ComFun.php'; use \helpComFun\ComFun as ComFun; //使用管理员访问 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('金新北路','汕头市'); echo '<br>通过命名空间获取位置:',ComFun::getShow('金新北路','汕头市'); }
ComFun.php
<?php namespace helpComFun; class ComFun { //获取位置 public static function getShow($arguments) { $place=func_get_arg(0); $city=func_get_arg(1); return $city.$place; } }
HelpClass.php
<?php class HelpClass { //获取位置 public function getShow($arguments) { $place=func_get_arg(0); $city=func_get_arg(1); return $city.$place; } } trait BiaoYu { public static function getBiaoYu() { return '欢迎来到'; } }
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'; //use BiaoYu; 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 BiaoYu::getBiaoYu() . parent::DIANMING; } //通过重载获取HelpClass的getShow方法 public function __Call($method,$arguments) { return call_user_func_array([(new HelpClass),'getShow'],$arguments); } }
效果图: