PHP容器类的两种实现方式示例
本文实例讲述了PHP容器类的两种实现方式。分享给大家供大家参考,具体如下:
通过魔术方法实现
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接口实现
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相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
相关推荐
聪聪李 2020-09-10
WasteLand 2020-09-15
辛苦的字幕君小样 2020-06-14
孙雪峰 2020-06-13
Crazyshark 2020-06-13
php工厂 2020-06-10
JF0 2020-05-20
hhxywlzx 2020-04-14
Skyline 2020-05-05
Havshark 2020-01-21
有梦就能实现 2019-11-09
stefan0 2019-10-16
ZhaoYanping00 2019-09-08
xcguoyu 2013-06-07
machao 2019-05-08
Purgatory00 2019-04-12