PHP Fatal error: Using $this when not in object context

后端 未结 9 2258
日久生厌
日久生厌 2020-11-22 03:48

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\');

9条回答
  •  长发绾君心
    2020-11-22 04:12

    If you are invoking foobarfunc with resolution scope operator (::), then you are calling it statically, e.g. on the class level instead of the instance level, thus you are using $this when not in object context. $this does not exist in class context.

    If you enable E_STRICT, PHP will raise a Notice about this:

    Strict Standards: 
    Non-static method foobar::foobarfunc() should not be called statically
    

    Do this instead

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

    On a sidenote, I suggest not to use global inside your classes. If you need something from outside inside your class, pass it through the constructor. This is called Dependency Injection and it will make your code much more maintainable and less dependant on outside things.

提交回复
热议问题