user3681788
user3681788

Reputation: 221

PHP using $this when not in object context

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.

Upvotes: 1

Views: 2195

Answers (1)

Danijel
Danijel

Reputation: 12689

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'

Upvotes: 3

Related Questions