Php函数返回错误

时间:2011-12-17 15:09:57

标签: php function

我的php函数返回错误。

这两个函数来自同一个类

错误 致命错误:在D:\ xampp \ htdocs \ admin \ functions.php(98)中不在对象上下文中时使用$ this:第1行的运行时创建函数

public function noFollowLinks($str) {
    // replaces every link with the version provided by fixLink()
    return preg_replace_callback("#(<a.*?>)#i", create_function('$matches', 'return $this->fixLink($matches[1]);'), $str);
}

public function fixLink($input) {
    $whitelist = $GLOBALS['whitelist'];
    // if the link in $input already contains ref=”nofollow”, return it as it is
    if (preg_match('#rel\s*?=\s*?[\'"]?.*?nofollow.*?[\'"]?#i', $input)) {
        return $input;
    }
    // extract the URL from $input
    preg_match('#href\s*?=\s*?[\'"]?([^\'"]*)[\'"]?#i', $input, $captures);
    // $href will contain the extracted URL, such as http://seophp.example.com
    $href = $captures[1];
    // if URL doesn’t contain http://, assume it’s a local link
    if (!preg_match('#^\s*http://#', $href)) {
        return $input;
    }
    // extract the host name of the URL, such as seophp.example.com
    $parsed = parse_url($href);
    $host = $parsed['host'];
    // if the URL is in the whitelist, send $input back as it is
    if (in_array($host, $whitelist)) {
        return $input;
    }
    // assuming the URL already has a rel attribute, change its value to nofollow
    $x = preg_replace('#(rel\s*=\s*([\'"]?))((?(3)[^\'"]*|[^\'"]*))([\'"]?)#i', '\\1\\3,nofollow\\4', $input);
    // if the string has been modified, it means it already had a rel attribute,
    // whose value has been changed to nofollow, so we return the new version
    if ($x != $input) {
        return $x;
    }
    // if the link in the input string doesn’t have ref attribute, we add it
    else {
        return preg_replace('#<a#i', '<a rel="nofollow"', $input);
    }
}

3 个答案:

答案 0 :(得分:1)

当使用闭包时,它在一个类之外充当一个单独的函数。它没有像其他方法(类中的函数)那样附加到类中,因此使用$ this会导致该错误,就像在类之外使用$ this一样

答案 1 :(得分:0)

你不能在闭包中使用$this,因为它不是一个对象。


你必须做这样的事情:

<?php

       class A {

              public $name ;

              public function doSomething ( Closure $closure ) {
                     return call_user_func_array ( $closure , array ( $this ) ) ;
              }

       }

       $A = new A ( ) ;
       $A->name = 'test' ;
       $A->doSomething(function($object){
              print_r ( $object ) ;
       });

答案 2 :(得分:0)

正如安德烈所说,你不能在$this创建的函数中使用create_function。 我对此的忠诚,就是用这个替换你的noFollowLinks

public function noFollowLinks($str) {
    // replaces every link with the version provided by fixLink()
    return preg_replace_callback("#(<a.*?>)#i", array($this, 'fixLinkCallback'), $str);
}

private function fixLinkCallback($matches) {
    return $this->fixLink($matches[1]);
}