主要的想法是利用call_user_func_array()和容器結合使用的。
核心程式碼,理解都在註解中:
<?php //reqeuestFacade.php namespace facade{ class Request extends Facade{ public function getFacadeName(){ return 'request'; } } } ?> <?php //facade.php namespace facade{ class Facade{ public static function createFacade(){ $class = static::class; //在这个获取的$class其实是facade\reqeust //在这里利用static::得到getFacadeName,返回真正的request的变量名 $facadeClass = static::getFacadeName(); if ($facadeClass) { $class = $facadeClass; } elseif (isset(self::$bind[$class])) { $class = self::$bind[$class]; } //echo $class; 利用容器去获取reqeust,而不是facade\reqeust return \Container::get($class); } public static function __callStatic($method, $params) { return call_user_func_array([static::createFacade(), $method], $params); } } } ?>
以下測試程式碼
#reqeust.php
<?php class Request{ public $name = 'Real Request'; public function sayName(){ echo $this->name; } } ?>
test.php
<?php use facade\Request; include "Container.php"; include "Facade.php"; include "RequestFacade.php"; include "Request.php"; Request::sayName(); ?>
推薦教學:thinkphp教學
#以上是在thinkphp中實作facade的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!