PHP静态变量

时间:2011-08-09 09:51:02

标签: php

我有一个做一些API(REST)函数的类。我想声明变量类范围变量和静态,所以我不会一遍又一遍地获取数据。 (这是我在理论上认为可能是错误的)类中的许多方法都需要这些数据。

我正在使用这种类型但看起来不对劲。它正在工作,但是 (这只是一个示例类,而不是真正的代码);

class Some_Process {

    private static $tickets = array();

    private function _get_tickets () {
        if(!self::$tickets) {
           $curl = curl_init();
           curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
           curl_setopt($curl, CURLOPT_URL, 'http://someurl');

           self::$tickets = json_decode(curl_exec($curl));
           if(!self::$tickets) {
               return FALSE;
           }
           return TRUE;
        }
    }
    function process_tickets () {
       self::_get_tickets();
       //here I start using the varible
       do some job on .. self::$tickets;
    }   
}

2 个答案:

答案 0 :(得分:1)

有一个问题,如果http://someurl返回的实际票数为零,怎么办?那么即使我们已经填充了数组,if(!self::$tickets)也将永远为真。我会使用$tickets初始化null

private static $tickets = null;

并将该条件更改为:

if( self::$tickets === null ) {
    self::$tickets = array();
    ...
}

答案 1 :(得分:0)

单身模式?

class Some_Process {
   protected static $_instance;
   private $_tickets = array();

   public static function initialiaze() {
       $curl = curl_init();
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
       curl_setopt($curl, CURLOPT_URL, 'http://someurl');

       self::getInstance(json_decode(curl_exec($curl));
   }

   public static function getInstance($tickets = null) {
       if (!self::$_instance) {
            self::$_instance = new self($tickets);
       }

       return self::$_instance;
   }

   private function __constructor($tickets) {
       $this->_$tickets = $tickets;
   }

   public function getTickets() {
       return $this->_tickets;
   }

   public function processTickets() {
       $this->_tickets();
       ...
   }
}

使用Singleton模式一次实例化对象,这样您就可以一次抓取票证。

当量:

Some_Process::initialize();
Some_Process::getInstance()->processTickets();