2012-01-30 283 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”类现在使用这些键作为班级成员

相关问题