PHP uses $ this if 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 if not in the context of an object in /var/www/programs/decode.php on line 38

Why is this happening? I suppose it has something to do with the parameter that the function has in preg_replace_callback

, but I have no idea how to fix it.

+1


source to share


1 answer


Since PHP 5.4 $this

can be used in anonymous functions and refers to the current object, a 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 can 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 to at least 5.4 if possible.

More information: PHP 5.4 - "closing $ this support"

+3


source







All Articles