php print_r 还原成数组的代码原理?

查看:116
本文介绍了php print_r 还原成数组的代码原理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

class Trie {  
  protected $dict = array();  
  protected $buf = '';  
  function set($word, $value='') {  
    if(is_array($word)) foreach($word as $k=>$v) $this->set($k, $v);  
    $p =& $this->dict;  
    foreach(str_split($word) as $ch) {  
        if(! isset($p[$ch])) $p[$ch] = array();  
        $p =& $p[$ch];  
    }  
    $p['val'] = $value;  
    return $this;  
  }  
  function parse($str) {  
    $this->doc = $str;  
    $this->len = strlen($str);  
    $i = 0;  
    while($i < $this->len) {  
        $t = $this->find($this->dict, $i);  
        if($t) {  
            $i = $t;  
            $this->buf = '';  
        }else $this->buf .= $this->doc{$i++};  
    }  
  }  
  protected function find(&$p, $i) {  
    if($i >= $this->len) return $i;  
    $t = 0;  
    $n = $this->doc{$i};  
    if( isset($p[$n]) ) $t = $this->find($p[$n], $i+1);  
    if($t) return $t;  
    if( isset($p['val']) ) {  
        $ar = explode(',', $p['val']);  
        call_user_func_array( array($this, array_shift($ar)), $ar );  
        return $i;  
    }  
    return $t;  
  }  
  function __call($method, $param) {  
    echo "****\n$this->buf 未定义方法:$method 参数:" . join(',', $param) . "<br />\n";  
  }  
}  
  
  
  
class App extends Trie {  
  public $res = array();  
  protected $stack = array();  
  protected $keyname = '';  
  protected $buf = '';  
  function __construct() {  
    $this->stack[] =& $this->res;  
  }  
  protected function group() {  
    if(! $this->keyname) return;  
    $cnt = count($this->stack) - 1;  
    $this->stack[$cnt][$this->keyname] = array();  
    $this->stack[] =& $this->stack[$cnt][$this->keyname];  
    $this->keyname = '';  
  }  
  protected function brackets($c) {  
    $cnt = count($this->stack) - 1;  
    switch($c) {  
        case ')':  
            if($this->keyname) $this->stack[$cnt][$this->keyname] = trim($this->buf);  
            $this->keyname = '';  
            array_pop($this->stack);  
            break;  
        case '[':  
            if($this->keyname) $this->stack[$cnt][$this->keyname] = trim($this->buf);  
            break;  
        case ']':  
            $this->keyname = $this->buf;  
    }  
    $this->buf = '';  
  }  
}

这段代码我在几个示例中看到,原始的出处不知道,它是如何实现print_r 的显示成数组呢?求注释,谢谢!
中间常用的是&,来回几个我就晕了。

解决方案

&代表引用,比如

$a = &$b;

就代表$a$b是同一个引用,修改$a也会修改$b的值,修改$b也影响$a。不加上&就代表把$b的值复制一份给$a,两者都是独立的。

而函数(方法)的参数列表里加上&,就代表按引用传递了,不加就是按值传递,这是编程的基本概念,不用多说了吧。

需要注意的是对象类型,不管加不加&都是引用。

这篇关于php print_r 还原成数组的代码原理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆