PHP,致命错误:未捕获错误:在不在对象上下文中时使用$ this

时间:2017-02-22 11:42:13

标签: php oop

我不明白为什么会出现这个错误。 我想在数据库中的数据中更改一些字符串,所以我使用了preg_replace_callback。但是当我在回调函数的定义中使用时

$row = $this->result->fetch_assoc();

解析器回复错误

所有代码:

    public function tRsql() {
        $argNums = func_num_args();
        $argsArr = func_get_args();

        function change($matches) {
            if(stripos($matches[0], "sql:")) {
                $str = ltrim($matches[0], "#sql:");
                $str = rtrim($str, ":");
                $row = $this->result->fetch_assoc();
                $str = $row[$str];
                return $str;
            } else {
                return $matches[0];
            }
        }
        for($i = 0; $i < $this->numOfRows; $i++) {
            $argsArr = preg_replace_callback("/(#sql\:)\S+\:/", "change", $argsArr);
            $this->tR(implode(",",$argsArr));
        }
    }

1 个答案:

答案 0 :(得分:0)

以这种方式做到:

public function tRsql() {
    $argNums = func_num_args();
    $argsArr = func_get_args();

    $change = function ($matches) {
        if(stripos($matches[0], "sql:")) {
            $str = ltrim($matches[0], "#sql:");
            $str = rtrim($str, ":");
            $row = $this->result->fetch_assoc();
            $str = $row[$str];
            return $str;
        } else {
            return $matches[0];
        }
    }
    for($i = 0; $i < $this->numOfRows; $i++) {
        $argsArr = preg_replace_callback("/(#sql\:)\S+\:/", $change, $argsArr);
        $this->tR(implode(",",$argsArr));
    }
}

在此处阅读更多内容:http://php.net/manual/en/functions.anonymous.php