[英]Fatal Error: Using $this when not in object context
I'm receiving this fatal error message: Using $this when not in object context.
我收到这个致命的错误消息:
Using $this when not in object context.
This class is setted up as a library in the CodeIgniter. 此类在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'm initializing it via autoload.php
. 我正在通过
autoload.php
初始化它。 The line it is throwing the error at: 它抛出错误的行:
file_put_contents( $this->app . $key.'.cache', $value);
Where is my problem? 我的问题在哪里?
You can't use $this
in a static method. 你不能在静态方法中使用
$this
。 The variable $this
is only available to class methods as these receive the object on which the method is called. 变量
$this
仅对类方法可用,因为它们接收调用方法的对象。
That's what "when not in object context" means: there's no object passed to that static method because it's static. 这就是“当不在对象上下文中”时意味着:没有对象传递给该静态方法,因为它是静态的。 A static method is part of the class, not part of the objects that are instantiated using that class.
静态方法是类的一部分,而不是使用该类实例化的对象的一部分。
$this
will not be available in a static function. $this
在静态函数中不可用。 You'll probably want to re-create $app
within the static function: 你可能想在静态函数中重新创建
$app
:
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 quite sure what you're trying to do in the grand context of your application, but you may not even need a static
method in the first place. 我不太确定你在应用程序的宏大环境中尝试做什么,但你可能首先不需要
static
方法。
To be honest, the store
function should be an instance function (remove static
keyword), otherwise using $this
within it will have no idea what object it's referring to. 说实话,
store
函数应该是一个实例函数(删除static
关键字),否则在其中使用$this
将不知道它指的是什么对象。
Alternatively, you could have objects pass in references to themselves so that the static function would know what object to act on: static function store($obj, $key, $value) [...] $obj->app [...]
或者,您可以让对象传递给自己的引用,以便静态函数知道要对其执行的对象:
static function store($obj, $key, $value) [...] $obj->app [...]
Or, just pass in the contents of $obj->app
since the static function only needs that piece of information and not access to the entire object: 或者,只需传入
$obj->app
的内容,因为静态函数只需要那条信息而不能访问整个对象:
static function store($app, $key, $value)
{
$key = sha1($key);
$value = serialize($value);
file_put_contents( $app . $key.'.cache', $value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.