函数调用自己

时间:2011-07-26 05:36:53

标签: php oop

再次出现另一个问题。

public function __construct() {
    $_GET = $this->clean($_GET);
    $_POST = $this->clean($_POST);
    ...

}

public function clean($data) {
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            unset($data[$key]);

            $data[$this->clean($key)] = $this->clean($value);
        }
    } else { 
        $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
    }

    return $data;
}

我不明白为什么$data[$this->clean($key)] = $this->clean($value);正在调用自己的函数。这样做有什么意义?优点

感谢, 丹尼尔

3 个答案:

答案 0 :(得分:6)

这是一种称为递归的技术。这个特殊的函数下降到结构中,直到它处理非常简单的数据并清理它。

鉴于此:

$arr = array (
   '<foo' => array(
       'bat' => 'OMGWTFBBQ!!><!?!'
   ),
   'bar' => 'baz'
);

它会开始:

  1. 是一个阵列吗?
    1. <foo一个数组? (没有)
      • <foo变为&lt;foo
      • &lt;foo用作键
    2. <foo数组的值? (是)
      1. 蝙蝠是阵列吗? (没有)
        • bat保持不变(仍调用htmlspecialchars,但不会改变任何内容))
      2. 'OMGWTFBBQ!!><!?!'是否为数组(否)?
        • 'OMGWTFBBQ!!><!?!'已转换为'OMGWTFBBQ!!&gt;&lt;!?!'
        • 'OMGWTFBBQ!!&gt;&lt;!?!'用于bat的值。
    3. 'bar'是阵列吗? (没有)
      1. bar按原样返回(如上面的蝙蝠)
      2. baz是阵列吗? (没有)
        • baz按原样返回。
  2. 你可以这样想到

    $arr = array (
       '<foo' => array(
           'bat' => 'OMGWTFBBQ!!><!?!'
       ),
       'bar' => 'baz'
    );
    
    ///////////////////////////////////////////
    array (
       clean('<foo') => array(
           'bat' => 'OMGWTFBBQ!!><!?!'
       ),
       'bar' => 'baz'
    );
    
    ///////////////////////////////////////////
    array (
       '&lt;foo' => clean( array(
           'bat' => 'OMGWTFBBQ!!><!?!'
       )),
       'bar' => 'baz'
    );
    
    ///////////////////////////////////////////
    array (
       '&lt;foo' => array(
           clean( 'bat' ) => 'OMGWTFBBQ!!><!?!'
       )),
       'bar' => 'baz'
    );
    
    ///////////////////////////////////////////
    array (
       '&lt;foo' => array(
           'bat' => clean( 'OMGWTFBBQ!!><!?!' )
       )),
       'bar' => 'baz'
    );
    
    ///////////////////////////////////////////
    array (
       '&lt;foo' => array(
           'bat' => 'OMGWTFBBQ!!&gt;&lt;!?!'
       )),
      clean( 'bar' ) => 'baz'
    );
    ///////////////////////////////////////////
    array (
       '&lt;foo' => array(
           'bat' => 'OMGWTFBBQ!!&gt;&lt;!?!'
       )),
      'bar' => clean( 'baz' )
    );
    ///////////////////////////////////////////
    return array (
       '&lt;foo' => array(
           'bat' => 'OMGWTFBBQ!!&gt;&lt;!?!'
       )),
      'bar' => 'baz'
    );
    

答案 1 :(得分:3)

clean函数使用htmlspecialchars从字符串中清除html字符。但如果$data是一个数组,它会调用自己来清理所有键和值。这就是为什么clean是递归的。

这种方法的优点是清洁函数可以透明地用于字符串和数组。

答案 2 :(得分:0)

它被称为recursion

在您的示例中,$ _GET和$ _POST数组可能包含的元素也是可以包含数组的数组(ad infinitum)。所以你不知道要清理多少个子阵列。

要解决此问题,函数clean的编写方式是在清理当前数组时它发生“子数组”时调用自身。它就像一个仅用于嵌套数据结构的循环。