我不喜欢“getProperty”和“setProperty”等函数,因此我研究了 __get 和 __set 函数。
我创建了一个运行良好的结构。现在我想在我的大部分类(class)中使用它。我该如何做到这一点(记住我可能想用另一个类扩展一个类)而不必重复代码?
我已经知道接口(interface)不是一个选项,因为这都是关于复制代码的(如果我理解正确的话)
以下是函数,以防万一:
/**
* 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;
}
}
最佳答案
如果我理解正确,您希望自动处理一组对象中的属性数组,如果是这样,那么这应该相应地工作:
abstract class Prototype
{
protected $properties = array();
public function __get($key)
{
if(property_exists($this,'properties') && is_array($this->properties))
{
return isset($this->properties[$key]) ? $this->properties[$key] : null;
}
}
public function __set($key,$value)
{
if(property_exists($this,'properties') && is_array($this->properties))
{
$this->properties[$key] = $value;
}
}
}
这只是一个基本概念,但我刚刚测试过并且工作正常,您只需像这样扩展根类即可:
class User extends Prototype{}
然后像通常使用 get 和 set 魔术方法设置值一样使用,将方法设置为 protected 将允许这些方法在所有子类中可用,但不允许在对象外部使用。
这是您要找的吗?
关于php - 为我的所有类实现/扩展/继承/...相同的 __get 和 __set 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6447391/