【发布时间】:2011-06-22 22:38:20
【问题描述】:
我不喜欢“getProperty”和“setProperty”之类的函数,所以我研究了 __get 和 __set 函数。
我创建了一个运行良好的结构。现在我想在我的大部分课程中使用它。我如何做到这一点(记住我可能想用另一个类扩展一个类)而不必复制代码?
我已经知道接口不是一个选项,因为这就是复制代码(如果我理解正确的话)
以下是函数,以防万一:
/**
* Simply return the property
*/
private function __get($strProperty) {
if(array_key_exists($strProperty, $this->properties)){
$c = $this->properties[$strProperty];
// Fetch the wanted data and store it in memory
if(!$c['fetched']){
if($c['type'] == 'array'){
$proptr = $this->md->fetch_array('SELECT ' . $c['field'] . ' FROM ' . $c['table'] . ' WHERE ' . $c['where'], $c['table'].$c['field'].$c['where'], 1000);
$c['value'] = $proptr;
}else {
$proptr = $this->md->query_first('SELECT ' . $c['field'] . ' FROM ' . $c['table'] . ' WHERE ' . $c['where'], $c['table'].$c['field'].$c['where'], 1000);
$c['value'] = $proptr[$c['field']];
}
}
return $c['value'];
} else {
return $this->$strProperty;
}
}
/**
* Set the property, and update the database when needed
*/
private function __set($strProperty, $varValue) {
// If the property is defined in the $properties array, do something special
if (array_key_exists($strProperty, $this->properties)) {
// Get the fieldname
$field = $this->properties[$strProperty]['field'];
$data[$field] = $varValue;
$this->md->update(TABLE_USER, $data, $this->properties[$strProperty]['where']);
// And store the value here, too
$this->$strProperty = $varValue;
} else {
$this->$strProperty = $varValue;
}
}
【问题讨论】:
-
ehm ...只是创建一个类并从它继承?那太容易了,因此恐怕我不明白您的真正问题:X
-
这真的有效吗?私有魔法函数?
-
@KingCrunch:真正的问题可能是,您只能从 PHP 中的一个类扩展。
-
哦,我从别人那里得到了这个想法,那里的魔法方法是私有的。无论哪种方式都可以,但是如果您可以放心,我会更改它;)无论如何:如果我将其放在一个类中并继承该类,则我无法继承其他任何东西。
-
@KingCrunch:我试过了;)你得到一个警告,并且该方法被强制公开。
标签: php