我上逻辑课。
类BlogApp
class BlogApp
{
public static $app;
public function __construct()
{
self::$app = Registry::instance();
$this->getParams();
}
课程注册表
class Registry
{
use TSingletone;
protected static $properties = [];
public function setProperty($name, $value)
{
self::$properties[$name] = $value;
}
public function getProperty($name)
{
if (isset(self::$properties[$name])) {
return self::$properties[$name];
}
return null;
}
public function getProperties()
{
return self::$properties;
}
我想在控制器中的任何地方使用我的类BlogApp {}来存储属性。例如
BlogApp::$app->setProperty('img_width', 1280);
$wmax = BlogApp::$app->getProperty('img_width');
和我的public / index.php
new \App\BlogApp();
但我有例外
Call to a member function getProperty() on null
如果我使用这个
$d = new BlogApp();
$d::$app->getProperty('img_width');
没问题。但是我想要
$wmax = BlogApp::$app->getProperty('img_width');
我的错误在哪里?
答案 0 :(得分:2)
您要在BlogApp类的构造函数中创建注册表的对象,因此要调用getProperty方法,您需要创建BlogApp的对象。
但是,如果要使用对该类的引用来调用getProperty函数,则不要在BlogApp构造函数中创建Registry的实例。
class BlogApp
{
public static $app;
// Create a function call get_instance
public static function get_instance()
{
// create instance of Registry class
self::$app = Registry::instance();
self::getParams();
return self::$app;
}
}
/*
* Call the getProperty funtion with reference of class.
* 1 - Object of the Registry is Creating When you call the static function get_instance.
* 2 - Once the object is created you can call the getProperty function.
*/
$wmax = BlogApp::get_instance()->getProperty('img_width');