Methods php类对所有实例执行一次
因此,我有一个类,它的构造函数下载一些xml,并将其读入属性中,供类使用。我多次实例化这个类,这个耗时的工作以完全相同的方式完成了三次。我能否以某种方式避免它(我想是使用静态方法/属性)?我的类应该只获得一次属性,然后每个实例都可以使用它们。我觉得我应该把代码放在一个静态函数中的构造函数之外,但我不知道它到底是如何完成的,因为我总是会出错Methods php类对所有实例执行一次,methods,properties,static,instance,self,Methods,Properties,Static,Instance,Self,因此,我有一个类,它的构造函数下载一些xml,并将其读入属性中,供类使用。我多次实例化这个类,这个耗时的工作以完全相同的方式完成了三次。我能否以某种方式避免它(我想是使用静态方法/属性)?我的类应该只获得一次属性,然后每个实例都可以使用它们。我觉得我应该把代码放在一个静态函数中的构造函数之外,但我不知道它到底是如何完成的,因为我总是会出错 class MyClass { protected $xml_file; protected $xml_derived_array; pu
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
}
}
应该是这样的:(但是我应该如何在我的_构造中调用静态属性,以及如何在静态函数中设置属性?)
编辑
这就是它现在的工作方式:
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;
}
}
您不需要静态方法。只需检查属性在构造函数中是否有值,如果没有,则获取xml文件并处理它
class MyClass {
protected static $xml_file;
protected static $xml_derived_array = array();
public function __construct($param1, $param2, $param3) {
if (! count(self::$xml_derived_array)){
//get xml_file and make xml_derived_array with it
//do some other stuff with parameters and properties such as $xml_derived_array
}
}
}
它不应该是self::$xml\u派生的\u数组吗?如果没有美元,这是行不通的。查看我的编辑,了解我现在是如何做的,以及它是如何工作的。
class MyClass {
protected static $xml_file;
protected static $xml_derived_array = array();
public function __construct($param1, $param2, $param3) {
if (! count(self::$xml_derived_array)){
//get xml_file and make xml_derived_array with it
//do some other stuff with parameters and properties such as $xml_derived_array
}
}
}