4

我有一个事件类,用于将数据插入/更新到我的数据库中。有没有办法可以从我的 db_fields 数组创建公共变量,这样我就不必复制数据了?

这是我目前有效的结构......

class event{
    protected static $table_name='tName';
    protected static $db_fields = array('field1','field2','field3','field4','field5');

    public $field1;
    public $field2;
    public $field3;
    public $field4;
    public $field5;
}

我想要这样的东西。。

class event{
    protected static $table_name='tName';
    protected static $db_fields = array('field1','field2','field3','field4','field5');

    function __construct() {
        create_public_vars_here($db_fields);
    }

}

谢谢!

4

3 回答 3

2

您可以尝试以下方法:

class event{

    protected static $table_name='tName';
    protected static $db_fields = array('field1','field2','field3','field4','field5');

    function __construct() {
        foreach (self::$db_fields as $var) {
            $this->$var = $whateverDefaultValue;
        }
        // After the foreach loop, you'll have a bunch of properties of this object with the variable names being the string values of the $db_fiels.
        // For example, you'll have $field1, $field2, etc and they will be loaded with the value $whateverDefaultValue (probably want to set it to null).
    }

}
于 2012-10-03T21:52:06.037 回答
2

您可以使用魔法设置器/获取器:

class event{

    protected static $table_name='tName';
    protected static $db_fields = array('field1','field2','field3','field4','field5');

    public function __get($key)
    {

        if(!in_array($key, static::$db_fields))
            throw new Exception( $key . " doesn't exist.");

        return $this -> $key;

    }

    public function __set($key, $value)
    {

        if(!in_array($key, static::$db_fields))
            throw new Exception( $key . " doesn't exist.");

        $this -> $key = $value;

    }   

}

这样您就可以确保不会点击列表之外的值:

$event -> field1 = 'hello';  // --> OK
$event -> field17 = 'hello'; // --> Exception: field17 doesn't exist

echo $event -> field1;  // --> OK
echo $event -> field17; // --> Exception: field17 doesn't exist

至于在你的代码中有一个显式的公共变量声明,你不需要迭代你的对象——但在这种情况下,你将Iterator基于你的静态字段实现接口。

于 2012-10-03T22:04:52.193 回答
0

使用突变器:

class event{
  protected static $table_name='tName';
  protected static $db_fields = array('field1','field2','field3','field4','field5');

  function getVars($var) {
    if(!in_arrary($this->db_fields[$var])) {
      return false;
    } else {
      return $this->db_fields[$var];
    }
  }
}

然后你可以像这样访问它:

$eventObject->getVars('field3');

或者,如果您不从类中创建对象:

event::getVars('field3');

编辑:本着使事情复杂化的精神,这样您就不会违反边界,添加了代码。

于 2012-10-03T21:50:23.023 回答