Fatal error: using $ this if not in object context
I am getting this fatal error: Using $this when not in object context.
This class is installed as a library in CodeIgniter.
This is my class:
class My_class {
function __construct()
{
$this->app = base_url('application') . '/cache/';
if ($this->expire_after == '')
{
$this->expire_after = 300;
}
}
static function store($key, $value)
{
$key = sha1($key);
$value = serialize($value);
file_put_contents( $this->app . $key.'.cache', $value);
}
}
I am initializing it via autoload.php
. The line raises an error:
file_put_contents( $this->app . $key.'.cache', $value);
Where is my problem?
source to share
$this
will not be available in a static function. You probably want to recreate $app
in a static function:
static function store($key, $value)
{
$app = base_url('application') . '/cache/';
$key = sha1($key);
$value = serialize($value);
file_put_contents( $app . $key.'.cache', $value);
}
I'm not really sure what you are trying to do in the main context of your application, but you might not even need a method static
.
source to share
You cannot use $this
in a static method. The variable $this
is only available to class methods, since they receive the object on which the method is called.
That "when not in the context of an object" means: there is no object passed to this static method because it is static. A static method is part of a class, not part of objects that are created using that class.
source to share
To be honest, the function store
must be an instance function (remove keyword static
), otherwise the usage $this
internally has no idea what object it refers to.
Alternatively, you could pass objects into references to themselves so that the static function can know which object to act on: static function store($obj, $key, $value) [...] $obj->app [...]
Or, just pass in the content $obj->app
, since a static function only needs this piece of information, not access to the entire object:
static function store($app, $key, $value)
{
$key = sha1($key);
$value = serialize($value);
file_put_contents( $app . $key.'.cache', $value);
}
source to share