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');

希望本文所述对大家PHP程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值