PHP使用$ this当不在对象上下文 [英] PHP using $this when not in object context

查看:356
本文介绍了PHP使用$ this当不在对象上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

  class Decode {
public $ code;
public $ codeStore;
public $ store;
public $ varName;
public $ storeNew = array();
public $ storeNew = array();

public function __construct($ code){
$ this-> code = $ code;
$ this-> codeStore = $ code;
$ this-> varName = substr($ this-> code,0,30);
$ this-> varName = str_replace(var,,$ this-> varName);
$ this-> varName = substr($ this-> varName,0,strpos($ this-> varName,= [\));
}

public function chrToVar(){
//下面的行是第38行
$ this-> code = preg_replace_callback('/'.$ this-> varName.'\ [ ([0-9] +)\] /',function($ matches){return $ this-> storeNew [$ matches [1]];},$ this-> code);
}
}

$ script = new Decode('stuff');
$ script-> chrToVar();
pre>

当我运行这个代码,我得到以下错误:


致命错误:在第38行的
/var/www/programs/decode.php中不在对象上下文中时使用$ this


为什么会发生这种情况?我想它与具有 preg_replace_callback 中的函数的参数有关,但我不知道如何解决它。

解决方案

您得到此错误的原因是由于范围。您定义的匿名函数有自己的范围,范围。为了使它工作,你必须传递variale $ this 到函数。这可以类似如下:

  function()use($ this){... 

希望它有帮助。


I have the following class:

class Decode {
    public $code;
    public $codeStore;
    public $store;
    public $varName;
    public $storeNew = array();
    public $storeNew = array();

    public function __construct($code) {
        $this->code = $code;
        $this->codeStore = $code;
        $this->varName = substr($this->code, 0, 30);
        $this->varName = str_replace("var ", "", $this->varName);
        $this->varName = substr($this->varName, 0, strpos($this->varName, "=[\""));
    }

    public function chrToVar() {
        // The line below is line 38
        $this->code = preg_replace_callback('/'.$this->varName.'\[([0-9]+)\]/', function($matches) { return $this->storeNew[$matches[1]]; }, $this->code);
    }
}

$script = new Decode('stuff');
$script->chrToVar();

When I run this code, I get the following error:

Fatal error: Using $this when not in object context in /var/www/programs/decode.php on line 38

Why is this happening? I suppose it has something to do with the parameter that has the function in preg_replace_callback, but I have no idea how to fix it.

解决方案

The reason you are getting this error is because of scope. The anonymous function you have defined has its own scope that is separate from the class scope. So to make it work you have to pass the variale $this to the function. This can be like the following:

function() use ($this) {...

Hope it helps.

这篇关于PHP使用$ this当不在对象上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆