我有一个我为工厂方法编写的类,我在第22行上遇到错误,其中指出:
致命错误:不在对象上下文中时使用$ this
我已经看过其他人的帖子和类似的问题,但是我不明白为什么能够应用他们所采取的措施作为我的情况的答案。
我的班级被称为:
$class = AisisCore_Factory_Pattern('class_you_want');
然后从那里执行以下操作:
class AisisCore_Factory_Pattern {
protected static $_class_instance;
protected static $_dependencies;
public function get_instance(){
if(self::$_class_instance == null){
$_class_instance = new self();
}
return self::$_class_instance;
}
public function create($class){
if(empty($class)){
throw new AisisCore_Exceptions_Exception('Class cannot be empty.');
}
if(null === self::$_dependencies){
$this->_create_dependecies();
}
if(!isset(self::$_dependencies['dependencies'][$class])){
throw new AisisCore_Exceptions_Exception('This class does not exist in the function.php dependecies array!');
}
if(isset(self::$_dependencies['dependencies'][$class]['arguments'])){
$new_class = new $class(implode(', ', self::$_dependencies['dependencies'][$class]['params']));
return $new_class;
}else{
$new_class = new $class();
return $new_class;
}
}
private function _create_dependecies(){
self::$_dependencies = get_template_directory() . '/functions.php';
}
}
它突然出现了:
$this->_create_dependecies();
我不确定这是如何脱离背景或我怎么称呼它......
答案 0 :(得分:0)
如果您不能使用$this
,则表示您正在使用{<1}}:
$this->_create_dependecies();
将其更改为:
self::_create_dependecies();
答案 1 :(得分:0)
因此,如果您尝试以单例形式执行此操作,则需要静态定义get_instance()方法。你如何调用create()?我完全没有提到这一点。也许create()应该是一个公共静态函数,然后更改你的$ this-&gt; _create_dependecies(); to self :: _ create_dependencies()并将static关键字添加到create_dependencies方法的定义中,因此它将是public static function create_dependencies。然后你把它全部放在一起......
$class = AisisCore_Factory_Pattern::create('class_you_want');
class AisisCore_Factory_Pattern {
protected static $_class_instance;
protected static $_dependencies;
public static function get_instance(){
if(self::$_class_instance == null){
$_class_instance = new self();
}
return self::$_class_instance;
}
public static function create($class){
if(empty($class)){
throw new AisisCore_Exceptions_Exception('Class cannot be empty.');
}
if(null === self::$_dependencies){
self::_create_dependecies();
}
if(!isset(self::$_dependencies['dependencies'][$class])){
throw new AisisCore_Exceptions_Exception('This class does not exist in the function.php dependecies array!');
}
if(isset(self::$_dependencies['dependencies'][$class]['arguments'])){
$new_class = new $class(implode(', ', self::$_dependencies['dependencies'][$class]['params']));
return $new_class;
}else{
$new_class = new $class();
return $new_class;
}
}
private static function _create_dependecies(){
self::$_dependencies = get_template_directory() . '/functions.php';
}
}
那应该做你。 如果你真的想非静态地访问它(是的我知道这不是一个真正的词,但我喜欢它)你应该说这样的话......
$class = AisisCore_Factory_Pattern::get_instance()->create('class_you_want');
//or...
$class = AisisCore_Factory_Pattern::get_instance();
$newclass = $class->create('class_you_want');
当然,在第二个示例中,您将从create function definition
中删除static关键字答案 2 :(得分:-1)
我相信你应该写$class = new AisisCore_Factory_Pattern("class_you_Want");