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

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

问题描述

我遇到了一个问题:

我正在写一个没有框架的新WebApp。

I'm writing a new WebApp without a Framework.

在我的 index.php im中使用: require_once('load.php');
和in * load.php * I 'm使用 require_once('class.php'); 加载我的 class.php

In my index.php im using: require_once('load.php'); and in * load.php* I'm using require_once('class.php'); to load my class.php.

在我的 class.php 中出现此错误:


致命错误:使用$这不是在对象上下文中的class.php on line ...(在这个例子中是11)

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

我的 class.php 写成:

class foobar {

    public $foo;

    public function __construct() {
        global $foo;

        $this->foo = $foo;
    }

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

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

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

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

foobar::foobarfunc();

,但也可以

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

为什么会出现错误?

推荐答案


在我的index.php我加载也许
foobarfunc()像这样:

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



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




/ p>

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();

您应改为使用:

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;
}

那么你可以使用:

foobar::foobarfunc();

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

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