2012-01-30 307 views
1

在我的班級我都像這樣定義在一個PHP類中,是否有一個簡單的方法來定義一個函數的變量?

class t { 
    var $settings = array(); 
} 

我將這些設置使用相當多的數組,所以不是所有的地方寫$this->settings['setting']我想部署一個功能,在自動定義這些設置局部變量。

private function get_settings() { 

      $array = $this->settings['array']; 
      $foreign_key = $this->settings['foreign_key']; 
      $limit = $this->settings['limit']; 
      $tableclassid = $this->settings['tableclassid']; 
      $pager = $this->settings['pager']; 
      $container = $this->settings['container']; 
      $extracolumn = $this->settings['extracolumn']; 
    } 

現在,我想要做的就是獲得這些變量並將它們用於類中的另一個函數。在示例

public function test() { 
    $this->get_settings(); 
    return $foreign_key; 
} 

,我想它返回$this->settings['foreign_key']

是有辦法做到這一點?或者我必須用get_settings()代碼塊的所有函數來處理所有的函數?

我欣賞的幫助..謝謝:)

回答

3

使用內置extract()功能,其提取的數組在當前範圍內各個變量。

extract($this->settings); 

如果需要修改這些局部變量以反映到原始數組中,請將它們作爲參考提取。

extract($this->settings, EXTR_REFS); 

我不能說我寧願自己使用這種方法,或者甚至建議您這樣做。在類的內部,將它們保留在數組屬性中更具可讀性和可理解性。一般來說,我從來沒有使用過extract()

+0

非常感謝你,那正是我一直在尋找的!:) – Logan 2012-01-30 20:32:27

+1

即使您控制了正在提取的內容,亂扔變量命名空間通常也不是一個好主意。 – 2012-01-30 20:33:04

+0

這當然完全符合OP的要求(+1),但我想評論一下:在更大的代碼庫中提取''使得很難看到變量實例化/來自哪裏,所以在我的_personal_的意見我只會謹慎使用。 – Wrikken 2012-01-30 20:33:45

1

只要通過它作爲一個屬性。事情是這樣的:

$class = new T(); 

然後:

$class->getSettings('varname'); 

而且在功能:

function get_settings($varname){ 
    return $this->settings[$varname]; 
} 

或者使用__get()過載功能:

公共職能__get($名) { return $ this-> settings [$ name]; }

,並調用它是這樣的:

$類 - > VARNAME;

(不存在的功能/類變量,將被髮送到了get()重載函數

1

你總是可以重載神奇功能:

<?php 

class DynamicSettings 
{ 
    /** 
    * Stores the settings 
    * @var array 
    **/ 
    protected $settings = array(); 

    /** 
    * Called when something like this: 
    * $dynset->name = value; 
    * is executed. 
    **/ 
    public function __set($name, $value) 
    { 
     $this->settings[$name] = $value; 
    } 

    /** 
    * Called when something like this: 
    * $value = $dynset->name; 
    * is executed. 
    **/ 
    public function __get($name) 
    { 
     if (array_key_exists($name, $this->settings)) 
     { 
      return $this->data[$name]; 
     } 
     $trace = debug_backtrace(); 
     trigger_error('Undefined dynamic property ' . $name . 
      ' in ' . $trace[0]['file'] . 
      ' on line ' . $trace[0]['line'], 
      E_USER_NOTICE); 
     return null; 
    } 

    /** 
    * Called when checking for variable existance 
    **/ 
    public function __isset($name) 
    { 
     return isset($this->settings[$name]); 
    } 

    /** 
    * Called when unsetting some value. 
    **/ 
    public function __unset($name) 
    { 
     unset($this->settings[$name]); 
    } 

} 

$dynset = new DynamicSettings(); 
$dynset->hello = "Hello "; // creates array key "hello" with value "Hello " 
$dynset->world = "World!"; // creates array key "world" with value "World!" 

echo $dynset->hello . $dynset->world; // outputs "Hello World!" 

儘量延長「DynamicSettings」類現在使用這些鍵作爲班級成員

相關問題