在我的类中,我定义了一个类似的数组
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()拥有的代码块来打乱所有函数?
我很感激你的帮助。。谢谢:)
使用内置的extract()
函数,该函数将数组提取到当前作用域中的各个变量中。
extract($this->settings);
如果需要修改这些局部变量以反映在原始数组中,请将它们提取为引用。
extract($this->settings, EXTR_REFS);
不过,我不能说我更喜欢自己使用这个方法,甚至不能建议你这样做。在类内部,将它们保留在数组属性中会更可读、更容易理解。一般来说,我从来没有真正使用过extract()
。
只需将其作为属性传递即可。类似这样的东西:
$class = new T();
然后:
$class->getSettings('varname');
在功能上:
function get_settings($varname){
return $this->settings[$varname];
}
或者使用__get()
过载功能:
公共函数__get($name){return$this->settings[$name];}
这样称呼它:
$class->varname;
(类中不存在的函数/变量,将被发送到get()重载函数
您总是可以重载神奇的函数:
<?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"类,并将这些键用作类成员。