PHP using $this when not in object context

人走茶凉 提交于 2019-12-11 12:26:55

问题


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.


回答1:


Since PHP 5.4 $this can be used in anonymous functions and it refers to the current object, simple example:

class Decode {
    public $code;

    public function __construct( $code ) {
        $this->code = $code;
    }

    public function chrToVar() {        
        $this->code = preg_replace_callback( '/\w+/', 
            function( $matches ) {              
                var_dump( $this );
            }, $this->code
        );
    }
}

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

For version 5.3 you may use a workaround but it only works with public properties:

$self = $this;
$this->code = preg_replace_callback( '/\w+/', 
    function( $matches ) use ( $self ) {                
        var_dump( $self );
    }, $this->code
);

My advice is to upgrade at least to 5.4 if possible.

More info: PHP 5.4 - 'closure $this support'



来源:https://stackoverflow.com/questions/27463584/php-using-this-when-not-in-object-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!