クラスのデフォルトのパブリック変数は、PHPの配列から動的に定義できますか?

StackOverflow https://stackoverflow.com//questions/12717399

質問

私はデータベースにデータを挿入/更新するために使用しているイベントクラスを持っています。データを複製しないように、私の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);
    }

}
.

ありがとう!

役に立ちましたか?

解決

次のことを試すことができます。

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).
    }

}
.

他のヒント

あなたはマジックセッター/ゲッターを使うことができます:

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
.

あなたのコードに明示的な公共変数宣言を持つことは、あなたのオブジェクトを反復する必要がない限り必要はありません - しかしこの場合は静的フィールドに基づく

モーテーターを使用:

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

編集:境界違反を持っていないように物事を複雑にするという精神では、コードが追加されました。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top