php类对所有实例都做一次

时间:2013-11-23 09:43:36

标签: methods properties static instance self

所以我有一个类,其构造函数下载一些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;
   }
}

1 个答案:

答案 0 :(得分:0)

您不需要静态方法。只需检查属性是否在构造函数中有值,如果没有,则获取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
      }
   }
}