网站建设资讯

NEWS

网站建设资讯

如何在PHP中实现一个容器类-创新互联

本篇文章给大家分享的是有关如何在PHP中实现一个容器类,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

成都创新互联是一家专注于成都做网站、成都网站制作与策划设计,唐县网站建设哪家好?成都创新互联做网站,专注于网站建设十年,网设计领域的专业建站公司;建站业务涵盖:唐县等地区。唐县做网站价格咨询:13518219792

通过魔术方法实现


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中实现一个容器类-创新互联
网站链接:http://cdweb.net/article/jpgop.html