开发者

Static methods requiring var

Ok, i'm stuck on this, why don't i get what i need?

class config
{

    private $config;

    # Load configurations
    public function __construct()
    {
        loadConfig('site'); // load a file with $cf in it
        loadConfig('database'); // load another file with $cf in it
        $this->config = $cf; // $cf is an array
        unset($cf);
    }

    # Get a configuration
    public static开发者_运维知识库 function get($tag, $name)
    {
        return $this->config[$tag][$name];
    }
}

I'm getting this:

Fatal error: Using $this when not in object context in [this file] on line 22 [return $this->config[$tag][$name];]

And i need to call the method in this way: config::get()...


public static function get

need to be

public function get

You can't use $this in static methods.

EDITED

I could do this, but I'm not sure if it's the best design for you.

class config
{

    static private $config = null;

    # Load configurations
    private static function loadConfig()
    {
        if(null === self::$config)
        {
            loadConfig('site'); // load a file with $cf in it
            loadConfig('database'); // load another file with $cf in it
            self::$config = $cf; // $cf is an array
        }
    }

    # Get a configuration
    public static function get($tag, $name)
    {
        self::loadConfig();
        return self::$config[$tag][$name];
    }
}


The problem is that you're Using $this when not in object context... Declaring a method as static removes the possibility to use the $this-reference inside the method.


There is no $this reference inside static methods as they belong to the class. Static methods can only access static members, so if it is important that get() is a static method, make $this->config a static member and return self::$config[$tag][$name]. However, the static keyword makes methods accessible without an instance of the class and I'd advise either making get() non-static, or making the class a singleton (depending on how you wish to use it).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜