PHP Error: Fatal error: Using $this when not in object context
public static function assign($name, $value)
{开发者_运维知识库
$this->params[] = array($name => $value);
}
public static function draw()
{
return $this->params;
}
}
<?php
$test = Templater::assign('key', 'value')->draw();
print_r($test);
I need to function "assign" was static, but $params was common for the whole class.. But this code is not working.
Fatal error: Using $this when not in object context
Any ideas?
It sounds like you want $params
to be static
:
<?php
class Templater
{
static $params = array();
public static function assign($name, $value)
{
self::$params[] = array($name => $value);
}
public static function draw()
{
return self::$params;
}
}
<?php
Templater::assign('key', 'value');
$test = Templater::draw();
print_r($test);
$this
keyword refers to the class instance. When you are trying to call it inside a static method no class instance is used. So your assign
method cannot be static to interact with $params
, that is not static. Make $params
static, or assign
dynamic (not static).
<?php
class Templater
{
static var $params = array();
public static function assign($name, $value)
{
$this->params[] = array($name => $value);
}
public static dunction draw()
{
return self::params;
}
}
or:
<?php
class Templater
{
var $params = array();
public function assign($name, $value)
{
$this->params[] = array($name => $value);
}
public dunction draw()
{
return $this->params;
}
}
Both will work, but you must to choose the one that is more adequate for your application's design.
Singleton would work nice here
class Templater {
private static $instance = null;
private $params = array();
public function __construct(){
return $this;
}
public static function instance(){
if(is_null(self::$instance)) self::$instance = new self();
return self::$instance;
}
public function assign($name, $value){
$this->params[$name] = $value;
return $this;
}
public function draw(){
return $this->params;
}
}
Usage:
$test = Templater::instance()
->assign('var1', 'value1')
->assign('var2', 'value2')
->draw();
print_r($test);
If you mean $params
to be a static field, use:
class Templater {
private static $params = array();
public static function assign($name, $value) {
self::params[] = array($name => $value);
}
public static dunction draw() {
return self::params;
}
}
static
functions have no $this
context.
By the way, don't use var
for declaring instance variables. That's PHP4. Do it the PHP5 way.
精彩评论