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');

    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

コードで明示的な public 変数宣言を行うことに関しては、オブジェクトを反復処理する必要がない限り必要ありませんが、この場合はIteratorstatic フィールドに基づいてインターフェイスを実装します。

于 2012-10-03T22:04:52.193 に答える
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 に答える