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

后端 未结 9 2243
日久生厌
日久生厌 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:08

    $foobar = new foobar; put the class foobar in $foobar, not the object. To get the object, you need to add parenthesis: $foobar = new foobar();

    Your error is simply that you call a method on a class, so there is no $this since $this only exists in objects.

    0 讨论(0)
  • 2020-11-22 04:09

    Fast method : (new foobar())->foobarfunc();

    You need to load your class replace :

    foobar::foobarfunc();
    

    by :

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

    or :

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

    Or make static function to use foobar::.

    class foobar {
        //...
    
        static function foobarfunc() {
            return $this->foo();
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 04:12

    It seems to me to be a bug in PHP. The error

    'Fatal error: Uncaught Error: Using $this when not in object context in'

    appears in the function using $this, but the error is that the calling function is using non-static function as a static. I.e:

    Class_Name
    {
        function foo()
        {
            $this->do_something(); // The error appears there.
        }
        function do_something()
        {
            ///
        }
    }
    

    While the error is here:

    Class_Name::foo();
    
    0 讨论(0)
  • 2020-11-22 04:12

    Just use the Class method using this foobar->foobarfunc();

    0 讨论(0)
  • 2020-11-22 04:15

    When you call the function in a static context, $this simply doesn't exist.

    You would have to use this::xyz() instead.

    To find out what context you're in when a function can be called both statically and in an object instance, a good approach is outlined in this question: How to tell whether I’m static or an object?

    0 讨论(0)
提交回复
热议问题