【问题标题】:"Fatal error: Using $this when not in object context" but code IS in object context“致命错误:不在对象上下文中使用 $this”但代码在对象上下文中
【发布时间】:2011-01-18 12:25:51
【问题描述】:

我得到了熟悉的“致命错误:不在对象上下文中使用 $this”,指的是以下类中的 $this->test = 'test';:

class Example {
    public $test;
    public function index() {
        $this->test = 'test';
    }
}

类方法通过call_user_func_array(array('example', 'index'), $params); 调用。我只能假设call_user_func_array 出于某种原因决定将索引方法称为静态方法,例如example::index()?但是我还没有找到解决方法,奇怪的是直到最近我才遇到问题。

【问题讨论】:

    标签: php oop


    【解决方案1】:

    这行得通:

    $obj = new Example();
    call_user_func_array(array($obj, 'index'), $params);
    

    您的代码基本上可以:

    Example::index($params);
    

    它静态调用index,你正确地假设了。

    【讨论】:

    • 忘了说我正在使用自动加载抱歉。我的印象是 call_user_func_array 无需手动实例化类。不是这样吗?
    • @Riddian 不。它不是。没有办法实际执行静态调用。顺便说一句:这种行为适用于所有接受回调的 PHP 函数(如 usort 等)。见Pseudo-types and variables...。
    猜你喜欢
    • 2010-12-11
    • 2011-01-21
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多