欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP容器类的两种实现方式示例

程序员文章站 2023-11-09 20:16:28
本文实例讲述了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');