致命错误:不在对象上下文中使用$this;当使用require - PHP时


"Fatal error: Using $this when not in object context" when using require - PHP

我读过很多类似的问题和答案,但似乎没有一个能解决我的情况。

class A{

 public function walk() {
     ...
 }
 public function dance() {
     require 'dance.php';    
 }
}

dance.php里面,我有

$this->walk();

我得到这个错误:致命错误:当不在对象上下文中使用$this

请帮助。是我不能在必需的文件中使用$this吗?

谢谢

我在一个干净的环境中测试了它,它对我来说工作得很好。

我假设你可能在代码的其他地方包含dance.php,而不是在对象上下文中。

也请看看可能访问$this从PHP类的include()'d文件?这可能是一个重复的问题。

刚刚测试过,应该可以运行(PHP 5.6)。

在我的dance.php只是<?php $this->walk();和远程方法被调用。错误一定是在别的地方。看起来你导入的文件不是在对象上下文中。


也许你应该使用特征。特征可以构建逻辑,并使它们与特定的类分离。

trait dance
{
    public function dance()
    {
        $this->walk();
    }
}
class A
{
    use dance;
    public function walk()
    {
        echo 'go forward';
    }
}
(new A())->dance();

实例:https://3v4l.org/g1Ybd