【问题标题】:PHP using $this when not in object context不在对象上下文中时 PHP 使用 $this
【发布时间】:2015-02-12 08:11:26
【问题描述】:

我有以下课程:

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();

当我运行此代码时,我收到以下错误:

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

为什么会这样?我想它与preg_replace_callback中具有该功能的参数有关,但我不知道如何修复它。

【问题讨论】:

标签: php function class fatal-error


【解决方案1】:

自 PHP 5.4 起,$this 可用于匿名函数,它引用当前对象,简单示例:

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();

对于 5.3 版,您可以使用一种解决方法,但它仅适用于公共属性:

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

如果可能,我的建议是至少升级到 5.4。

更多信息:PHP 5.4 - 'closure $this support'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多