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

I was accessing an instance of my instance with a constructor with the variable $ this; In all other method, this seems good when I call $this->event->method() , but with this method it throws me an error

Using $ this if not in the context of an object

I just did a research on this issue and the answers I found related to the PHP version, but I have version 5.4. what could be the problem?

This is the method I'm trying to call an 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; } 
+6
source share
1 answer

You cannot use $this when in a static method. Static methods do not know about the state of an object. You can only refer to static properties and objects using self:: . If you want to use the object itself, you need to feel that you are outside the class, so you need to make an instance of one, but this will not be able to understand what happened before in the object. That is, if some method changed the $_x property to some value, when you restore 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 like static self::method() , but in newer versions of PHP you will get errors for this, so it's best not to do this.

You can find information about this in the official php documentation: http://www.php.net/manual/en/language.oop5.static.php

Since static methods can be called without instantiating 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 warning level.

+15
source

All Articles