为什么array(className,“ privateFunctionName”)返回私有函数?

问题描述 投票:0回答:2
class someClass
{
    public function truncate($content, $amount = false)
    {

        if (!$amount || preg_match_all("/\s+/", $content, $junk) <= $amount) return $content;

        $content = preg_replace_callback("/(<\/?[^>]+\s+[^>]*>)/", array($this, '_shield'), $content);

        ......

        return $truncate;
    }

    ... 

    private function _shield($matches)
    {
        return preg_replace("/\s/", "\x01", $matches[0]);
    }

    ...

    private function _unshield($strings)
    {
        return preg_replace("/\x01/", " ", $strings);
    }

    ...
}

根据PHP Manualpreg_replace_callback的第二个参数应该是一个处理函数,在上面的代码中,它是array($this, '_shield'),我相信它会返回该类的私有函数之一“ _shield”。有人可以向我解释为什么array(class,privateFunctionName)将返回私有函数吗?是否有关于此的PHP手册页?

php arrays regex preg-replace-callback
2个回答
0
投票

根据手册,第二个参数应为callable(如manual中所定义),并且array($this, '_shield')是正确的:它确定$this->_shield()应该用作处理函数替换


0
投票

[如果查看Callbacks / Callables的示例,则会看到指定对象和类方法array('object/class, 'method')的不同方法。

如果您想知道为什么要使用私有,那是因为$this是当前对象,当然可以访问它自己的私有方法。

如果另一个类别中的array('someDifferentClass', '_shield')array($someObj, '_shield'),则[_shield()private将不起作用。

您也可以使用匿名功能:

$content = preg_replace_callback("/(<\/?[^>]+\s+[^>]*>)/",
                                 function($M) {
                                     return $this->_shield($v);
                                 }, $content);
© www.soinside.com 2019 - 2024. All rights reserved.