1
class A {
    $props = array('prop1', 'prop2', 'prop3');
}

上記で定義された配列をクラスプロパティに変換する方法は?最終結果は次のようになります。

class A {
    $props = array('prop1', 'prop2', 'prop3');
    public $prop1;
    public $prop2;
    public $prop3;
}

私はこれまでこれを試しました:

public function convert(){
        foreach ($this->props as $prop) {
            $this->prop;
        }
    }

私はphpに慣れていないので少し醜いように見えます

4

1 に答える 1

2

PHP のマジック メソッド __getを次のように使用できます__set(実装する前に、いつ、どのように呼び出されるかを調べてください)。

class A {
    protected $props = array('prop1', 'prop2', 'prop3');

    // Although I'd rather use something like this:
    protected GetProps()
    {
        return array('prop1', 'prop2', 'prop3');
    }
    // So you could make class B, which would return array('prop4') + parent::GetProps()

    // Array containing actual values
    protected $_values = array();

    public function __get($key)
    {
        if( !in_array( $key, GetProps()){
            throw new Exception("Unknown property: $key");
        }

        if( isset( $this->_values[$key])){
            return $this->_values[$key];
        }

        return null;
    }

    public function __set( $key, $val)
    {
        if( !in_array( $key, GetProps()){
            throw new Exception("Unknown property: $key");
        }
        $this->_values[$key] = $val;
    }
}

そして、それを通常のプロパティとして使用します:

$instance = new A();
$a->prop1 = 'one';
$tmp = $a->undef; // will throw an exception

また、次のように実装するとよいでしょう。

  • public function __isset($key){}
  • public function __unset($key){}

一貫性のある完全なクラスを受講できます。

于 2012-10-05T06:19:22.053 に答える