PHP容器类的两种实现方式示例
发布:smiling 来源: PHP粉丝网 添加日期:2021-12-07 15:52:48 浏览: 评论:0
这篇文章主要介绍了PHP容器类的两种实现方式,结合实例形式分析了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');
Tags: PHP容器类
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)