PHP容器类的两种实现方式示例
程序员文章站
2022-06-14 14:27:33
本文实例讲述了php容器类的两种实现方式。分享给大家供大家参考,具体如下:
通过魔术方法实现
class
class magiccontainer{
p...
本文实例讲述了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');
上一篇: 加快Vue项目的开发速度的方法
下一篇: 龙梅子真名叫什么,怎样的梅子好吃