【发布时间】:2013-12-08 06:35:44
【问题描述】:
所以我有一个类,它的构造函数会下载一些 xml 并将其读入属性以供该类使用。我将这个类实例化了几次,这个耗时的工作以完全相同的方式完成了三遍。我可以以某种方式避免它(我猜是使用静态方法/属性)吗?我的班级应该只获取一次属性,然后每个实例都可以使用它们。我觉得我应该把代码从我的构造函数中放到一个静态函数中,但是我不知道它是如何完成的,因为我总是出错。
class MyClass {
protected $xml_file;
protected $xml_derived_array;
public function __construct($param1, $param2, $param3) {
//get xml_file and make xml_derived_array with it
//do some other stuff with parameters and properties such as $xml_derived_array
}
}
应该变成这样:(但我应该如何在我的 __construct 中调用静态属性以及如何在静态函数中设置属性?)
class MyClass {
protected static $xml_file;
protected static $xml_derived_array;
protected static function get_xml() {
//get xml_file and make xml_derived_array with it (?how exactly?)
}
public function __construct($param1, $param2, $param3) {
self::get_xml();
//do some other stuff with parameters and properties such as $xml_derived_array (?how exactly?)
}
}
编辑 这就是它现在的工作方式:
class MyClass {
protected static $xml_file;
protected static $xml_derived_array = array();
public function __construct($param1, $param2, $param3) {
if (!self::$xml_file) {
self::$xml_file = simplexml_load_file('xml_file.xml');
self::$xml_derived_array[0] = self::$xml_file->title;
}
echo self::$xml_derived_array[0].$param1;
}
}
【问题讨论】:
标签: methods properties static instance self