PHP 致命错误:不在对象上下文中使用 $this [英] PHP Fatal error: Using $this when not in object context

查看:29
本文介绍了PHP 致命错误:不在对象上下文中使用 $this的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题:

我正在编写一个没有框架的新 Web 应用程序.

在我的 index.php 中我使用:require_once('load.php');

load.php 中,我使用 require_once('class.php'); 加载我的 class.php.

在我的 class.php 中,我遇到了这个错误:

<块引用>

致命错误:当不在 class.php 中的对象上下文中时使用 $this 在线...(在本例中为 11)

我的 class.php 是如何编写的示例:

class foobar {公共 $foo;公共函数 __construct() {全球 $foo;$this->foo = $foo;}公共函数 foobarfunc() {返回 $this->foo();}公共函数 foo() {返回 $this->foo;}}

在我的 index.php 中,我可能像这样加载 foobarfunc():

foobar::foobarfunc();

但也可以

$foobar = 新的 foobar;$foobar->foobarfunc();

为什么会出现错误?

解决方案

在我的 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();

这篇关于PHP 致命错误:不在对象上下文中使用 $this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆