Функция Php возвращает ошибку - PullRequest
0 голосов
/ 17 декабря 2011

Моя функция php возвращает ошибку.

эти две функции из одного класса

ошибка Неустранимая ошибка: использование $ this, когда он не находится в контексте объекта в D: \ xampp \ htdocs \ admin \ functions.php (98): созданная во время выполнения функция в строке 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 ]

1 голос
/ 17 декабря 2011

При использовании замыкания оно действует как отдельная функция вне класса.Он не привязан к классу, как другие методы (функции внутри класса), поэтому использование $ приведет к этой ошибке, как если бы вы использовали $ this вне класса

0 голосов
/ 17 декабря 2011

Как сказал Андрей, вы не можете использовать $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]);
}
0 голосов
/ 17 декабря 2011

Вы не можете использовать $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 ) ;
       });
...