• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

ArrayObject扩展的应用示例代码_php

php 搞代码 7年前 (2018-06-21) 158次浏览 已收录 0个评论

Zend_Config很好用,我比较喜欢它的数组形态,其实ArrayObject也可以做同样的事情

<?php
$config = array(
    ‘db’ => array (
        ‘adapter’ => ‘mysql‘,
        ‘config’ => array (

http://www.gaodaima.com/48287.htmlArrayObject扩展的应用示例代码_php

            ‘host’ => ‘localhost’,
            ‘port’ => ‘3306’,
            ‘dbname’ => ‘mydbname’,
            ‘username’ => ‘dbuser’,
            ‘password’ => ‘dbpassword’,
            ‘charset’ => ‘utf8’,
            ‘prefix’ => ”,
        ),
    ),
);
$config = new Zend_Config($config);
echo $config->db->adapter;
foreach ($config->db->config as $k => $v) {
    echo “$k | $v /n”;
}
echo count($config);
//… 甚至其他更多的方法

下面的扩展,通过几个魔术方法,不仅可以实现Zend_Config可以做到的事情,还可以继承Array_Object所有的可用方法

<?php
 
/**
 * 将数组转换为对像形态使用
 *
 * @package    core
 * @author     Akon(番茄红了) <[email protected]>
 * @copyright Copyright (c) 2008 (http://www.tblog.com.cn)
 * @license    http://www.gnu.org/licenses/gpl.html     GPL 2
 */
class Extend_ArrayObject extends ArrayObject
{
 
    /**
     * 构造方法
     *
     * @param array  $array
     */
    public function __construct(array $array = array())
    {
        foreach ($array as &$value)
            is_array($value) && $value = new self($value);
        parent::__construct($array);
    }
 
    /**
     * 使用魔术方法通过指定 name 获取值
     *
     * @param string  $index
     * @return mixed
     */
    public function __get($index)
    {
        return $this->offsetGet($index);
    }
 
    /**
     * 使用魔术方法修改指定 name 的值
     *
     * @param string  $index
     * @param mixed   $value
     */
    public function __set($index, $value)
    {
        $this->offsetSet($index, $value);
    }
 
    /**
     * 通过魔术方法判断数据是否已被设置
     *
     * @param string  $index
     * @return boolean
     */
    public function __isset($index)
    {
        return $this->offsetExists($index);
    }
 
    /**
     * 通过魔术方法删除数据
     *
     * @param string  $index
     */
    public function __unset($index)
    {
        $this->offsetUnset($index);
    }
 
    /**
     * 将数据信息转换为数组形式
     *
     * @return array
     */
    public function toArray()
    {
        $array = $this->getArrayCopy();
        foreach ($array as &$value)
            ($value instanceof self) && $value = $value->toArray();
        return $array;
    }
 
    /**
     * 将数据组转换为字符串形式
     *
     * @return array
     */
    public function __toString()
    {
        return var_export($this->toArray(), true);
    }
 
}

欢迎大家阅读《ArrayObject扩展的应用示例代码_php》,跪求各位点评,若觉得好的话请收藏本文,by 搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:ArrayObject扩展的应用示例代码_php
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址