【问题标题】:Why do I get the error: "Using $this when not in object context in.........."为什么我会收到错误消息:“不在对象上下文中使用 $this ......”
【发布时间】:2012-06-22 01:07:34
【问题描述】:

$title = 'question' ;) 在此先感谢,我似乎无法弄清楚。

class myClass {

    public $myVar = 'hello';

    public function myMethod() {
        echo $this->myVar;
    }

}

【问题讨论】:

  • 似乎 php 引擎告诉你,你使用 $this 的方式错误。 $this 应该用于分配值,获取值。 $this 是对自身的引用,即当前类。
  • 谢谢,直到现在我才注意到你的回复。我确实用错了。

标签: php oop this


【解决方案1】:

你在做什么:

myClass::myMethod();

或者:

$foo = new myClass();
$foo->myMethod();

【讨论】:

  • 实际上我的课程是在一个wordpress插件中。因为我不断收到错误,所以我只是将其简化为这一点。正在从 wordpress 函数 (add_menu_page) 调用该类的方法。我还没有从其他地方给班级打电话。我想我应该这样做?当这个 wordpress 函数调用该方法时,它是如何工作的?它是创建类的新实例,还是只是调用类中的方法而不实际启动类本身?
  • @JesperPurola 我对 wordpress 不够熟悉,在您剥离它之前它是一种静态方法吗?发布更多代码,也许是原始代码?电话呢?
  • 没关系,我已经弄清楚了... wordpress 将该方法称为静态方法。我必须首先让 MyClass 成为一个对象。你的指针帮助我找到了答案!
猜你喜欢
  • 2021-02-09
  • 2015-01-25
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-12
相关资源
最近更新 更多