且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP 致命错误:不在对象上下文中使用 $this

更新时间:2023-11-15 08:09:52

在我的 index.php 中,我可能正在加载foob​​arfunc() 像这样:

 foobar::foobarfunc();//错,不是静态方法

但也可以

$foobar = 新的 foobar;//正确的$foobar->foobarfunc();

您不能以这种方式调用方法,因为它不是静态方法.

foobar::foobarfunc();

你应该使用:

foobar->foobarfunc();

但是,如果您创建了一个静态方法,例如:

static $foo;//您的***变量设置为静态公共静态函数 foo() {返回 self::$foo;}

然后你可以使用这个:

foobar::foobarfunc();

I've got a problem:

I'm writing a new WebApp without a Framework.

In my index.php I'm using: require_once('load.php');

And in load.php I'm using require_once('class.php'); to load my class.php.

In my class.php I've got this error:

Fatal error: Using $this when not in object context in class.php on line ... (in this example it would be 11)

An example how my class.php is written:

class foobar {

    public $foo;

    public function __construct() {
        global $foo;

        $this->foo = $foo;
    }

    public function foobarfunc() {
        return $this->foo();
    }

    public function foo() {
        return $this->foo;
    }
}

In my index.php I'm loading maybe foobarfunc() like this:

foobar::foobarfunc();

but can also be

$foobar = new foobar;
$foobar->foobarfunc();

Why is the error coming?

In my index.php I'm loading maybe foobarfunc() like this:

 foobar::foobarfunc();  // Wrong, it is not static method

but can also be

$foobar = new foobar;  // correct
$foobar->foobarfunc();

You can not invoke method this way because it is not static method.

foobar::foobarfunc();

You should instead use:

foobar->foobarfunc();

If however you have created a static method something like:

static $foo; // your top variable set as static

public static function foo() {
    return self::$foo;
}

then you can use this:

foobar::foobarfunc();