Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
  }
like image 775
Fabrizio Fenoglio Avatar asked Jan 25 '14 11:01

Fabrizio Fenoglio


1 Answers

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.

like image 113
Royal Bg Avatar answered Sep 20 '22 11:09

Royal Bg