Php 需要var的静态方法
好吧,我被困在这上面了,为什么我不能得到我需要的Php 需要var的静态方法,php,static,Php,Static,好吧,我被困在这上面了,为什么我不能得到我需要的 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 i
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];
}
}
我明白了:
Fatal error: Using $this when not in object context in [this file] on line 22 [return $this->config[$tag][$name];]
我需要以这种方式调用该方法:
config::get()
..公共静态函数get
需要
公共函数get
不能在静态方法中使用$this
已编辑
我可以这样做,但我不确定这是否是最适合你的设计
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];
}
}
公共静态函数get
需要
公共函数get
不能在静态方法中使用$this
已编辑
我可以这样做,但我不确定这是否是最适合你的设计
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];
}
}
问题是,当不在对象上下文中时,
正在使用$this
。。。将一个方法声明为静态,就不可能在该方法中使用$this
-引用。问题在于,当不在对象上下文中时,您正在使用$this。。。将一个方法声明为static将消除在方法内部使用$this
-引用的可能性。静态方法内部没有$this
引用,因为它们属于类。静态方法只能访问静态成员,因此如果get()
是一个静态方法很重要,请将$this->config
设置为静态成员,并返回self::$config[$tag][$name]
。但是,static关键字使方法可以在没有类实例的情况下访问,我建议将get()
设置为非静态,或者将类设置为单例(取决于您希望如何使用它)。静态方法中没有$this
引用,因为它们属于类。静态方法只能访问静态成员,因此如果get()
是一个静态方法很重要,请将$this->config
设置为静态成员,并返回self::$config[$tag][$name]
。但是,static关键字使方法可以在没有类实例的情况下访问,我建议将get()
设置为非静态,或者将类设置为单例(取决于您希望如何使用它)。静态函数在类的上下文中调用,并且没有对任何特定实例的引用。静态函数在类的上下文中调用,没有对任何特定实例的引用。我需要在没有实例的情况下以config::get()的形式调用方法get()。然后$config属性需要是静态的,在这种情况下,您不能有构造函数。在这个例子中,我需要在没有实例的情况下以config::get()的形式调用方法get(),然后$config属性需要是静态的,在这种情况下,您不能有构造函数。看这个例子