【问题标题】:php class do once for all instancesphp 类对所有实例执行一次
【发布时间】: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


    【解决方案1】:

    您不需要静态方法。只需检查属性在构造函数中是否有值,如果没有,则获取 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_derived_array 吗?没有 $ 它不起作用。看看我的编辑,看看我现在是怎么做的,它是有效的。
    猜你喜欢
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    相关资源
    最近更新 更多