2012-10-05 53 views
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

+0

@Vyktor爲您編輯支票 –

回答

2

您可以使用php magic methods__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){}

,所以你必須保持一致和完整的課程。

+0

感謝您的幫助 –

相關問題