Using $this when not in object context - Laravel 4 PHP 5.4.12

前端 未结 1 829
别那么骄傲
别那么骄傲 2021-01-12 08:30

I was attemping to access on my instance on the constructor with the variable $this; In all other method it seem work good when i call $this->event->method()

相关标签:
1条回答
  • 2021-01-12 09:06

    You cannot use $this when you are in static method. Static methods are not aware of the object state. You can only refer to static properties and objects using self::. If you want to use the object itself, you need to feel like you are out of the class, so you need to make instance of one, but this will fail to understand what has happened before in the object. I.e. if some method changed property $_x to some value, when you reinstance the object, you will lose this value.

    However, in your case you can do

    $_this = new self;
    $_this->event->create($info);
    

    You can also call non static methods as static self::method() but in newer versions of PHP you will get errors for this, so it's better to not do it.

    The information about it, you can find in the official php documentation: http://www.php.net/manual/en/language.oop5.static.php

    Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static


    Calling non-static methods statically generates an E_STRICT level warning.

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