容器类的两种实现方式
2018-03-12 10:23
225 查看
原文地址:http://blog.csdn.net/koastal/article/details/72528456
通过魔术方法实现
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]); } } }
使用
$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接口实现
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]); } } }
使用
$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]); } } }
使用
$container = new Container(); $container['logger'] = function ($msg){ file_put_contents('info.log',$msg.PHP_EOL,FILE_APPEND); }; $logger = $container->logger; $logger('container works');
相关文章推荐
- spring容器框架定时任务实现的两种方式
- C++STL::两种方式实现STL容器的reference语义
- jquery lazyload 和 echo 两种方式实现图片延迟加载
- 基于Maven的SpringBoot项目实现热部署的两种方式
- 在Web应用中创建Spring容器的两种方式
- 快排的c++实现(两种实现方式)
- TabHost两种实现方式
- Java多线程系列--“基础篇”02之 常用的实现多线程的两种方式
- 通过编码和xml文件两种方式实现tween动画
- Android BottomSheet效果的两种实现方式
- 将HTML特殊转义为实体字符的两种实现方式
- java 实现websocket的两种方式
- java中单例设计模式的两种实现方式
- C#和C++实现强制结束进程的两种实现方式
- JavaScript进阶设计模式系列——基础篇——闭包(5)--命令模式的两种实现方式
- 理解生产者和消费者,两种实现方式
- java Thread编程(三) 同步的两种不同实现方式
- java图的邻接表实现两种方式及实例应用分析
- 二分查找的两种实现方式
- 13、生产者消费者模型_两种实现方式