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

青春壹個敷衍的年華 提交于 2020-01-21 06:51:47

问题


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() but on this method it throw me an error

Using $this when not in object context

I just did a research about this issue and the answers i found was all about the version of PHP but i have the version 5.4. what can be the issue?

This is the method that i try to call the instance.

// all protected variable $event , $team , $app
function __construct(EventTeamInterface $event,TeamInterface $team) {
    $this->event = $event;
    $this->team = $team;
    $this->app = app();
  }

  /**
  * @param $infos array() | 
  * @return array() | ['status'] | ['msg'] | ['id']
  */
  public static function createEvent($infos = array()){
      $create_event = $this->event->create($infos);
        if ($create_event) {
            $result['status'] = "success";
            $result['id'] = $create_event->id;
        } else {
            $result['status'] = "error";
            $result['msg'] = $create_event->errors();
        }

        return $result;
  }

回答1:


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.



来源:https://stackoverflow.com/questions/21349732/using-this-when-not-in-object-context-laravel-4-php-5-4-12

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!