本篇文章給大家分享的是有關(guān)如何在PHP中實(shí)現(xiàn)一個(gè)容器類,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
成都創(chuàng)新互聯(lián)是一家專注于成都做網(wǎng)站、成都網(wǎng)站制作與策劃設(shè)計(jì),唐縣網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)十年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:唐縣等地區(qū)。唐縣做網(wǎng)站價(jià)格咨詢:13518219792通過魔術(shù)方法實(shí)現(xiàn)
class
class MagicContainer{ private $ele; function __construct() { $this->ele = []; } function __set($name, $value) { $this->ele[$name] = $value; } function __get($name) { return $this->ele[$name]; } function __isset($name) { return isset($this->ele[$name]); } function __unset($name) { if(isset($this->ele[$name])){ unset($this->ele[$name]); } } }
usage
$container = new MagicContainer(); $container->logger = function ($msg){ file_put_contents('info.log',$msg.PHP_EOL,FILE_APPEND); }; $logger = $container->logger; $logger('magic container works');
通過ArrayAccess接口實(shí)現(xiàn)
class
class ArrayContainer implements ArrayAccess { private $elements; public function __construct() { $this->elements = []; } public function offsetExists($offset){ return isset($this->elements[$offset]); } public function offsetGet($offset){ if($this->offsetExists($offset)){ return $this->elements[$offset]; }else{ return false; } } public function offsetSet($offset, $value){ $this->elements[$offset] = $value; } public function offsetUnset($offset){ if($this->offsetExists($offset)){ unset($this->elements[$offset]); } } }
usage
$container = new ArrayContainer(); $container['logger'] = function ($msg){ file_put_contents('info.log',$msg.PHP_EOL,FILE_APPEND); }; $logger = $container['logger']; $logger('array container works');
Container
class
class Container implements ArrayAccess { private $elements; public function __construct() { $this->elements = []; } public function offsetExists($offset){ return isset($this->elements[$offset]); } public function offsetGet($offset){ if($this->offsetExists($offset)){ return $this->elements[$offset]; }else{ return false; } } public function offsetSet($offset, $value){ $this->elements[$offset] = $value; } public function offsetUnset($offset){ if($this->offsetExists($offset)){ unset($this->elements[$offset]); } } function __set($name, $value) { $this->elements[$name] = $value; } function __get($name) { return $this->elements[$name]; } function __isset($name) { return isset($this->elements[$name]); } function __unset($name) { if(isset($this->elements[$name])){ unset($this->elements[$name]); } } }
usage
$container = new Container(); $container['logger'] = function ($msg){ file_put_contents('info.log',$msg.PHP_EOL,FILE_APPEND); }; $logger = $container->logger; $logger('container works');
以上就是如何在PHP中實(shí)現(xiàn)一個(gè)容器類,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。