2015-03-02 108 views
0

我正在尋找一種方法來維護$this->property = "value"語法,但使用getter和setter方法。聲明屬性訪問器

我發現了幾個對魔術功能__get()__set()的引用,但是我正在尋找更多的基於個案的訪問器。

然後我發現這個:https://wiki.php.net/rfc/propertygetsetsyntax-v1.2,這看起來像我正在尋找的,但唉,似乎並沒有實施。

有沒有辦法做到這一點,沒有類功能來檢查每個屬性分配?

回答

0

對於我來說,你有兩個選擇:

  1. 你想用魔術方法來覆蓋所有的getter和setter,你會存儲你的數據,將在像$這樣的屬性來獲得/套 - > _ data []以避免與其他屬性衝突
  2. 您想要創建特定的getter/setter,並且手動將它們定義在希望它們用於的類中(或者調高繼承鏈以便它們可用於每個擴展它的類 - 在MVC體系結構中很有用)。

神奇的方法方法是一種很好的「覆蓋所有基礎」的方法,而單獨的方法更好地清晰並且準確地知道實現/子級可用的東西。

選項1(魔術方法)的一個很好的例子是available in the manual, here

我想補充一點,如果你想爲性基礎「逐案」,你還可以添加白名單/黑名單到你的魔術方法包含/排除一組特定的屬性,例如延長什麼手冊:

private $data = array(); 
private $whitelist = array('PropertyIWant', 'AnotherOneIWant'); 

// ... 

    public function __get($name) 
    { 
     // ... 
     if (array_key_exists($name, $this->data) && in_array($name, $this->whitelist)) { 
      return $this->data[$name]; 
     } 
     // ... 
0

您可以使用電話:

class Test { 
    protected $a; 

    protected $b; 

    protected $valueForC; 

    protected $otherData = array('d' => null); 

    public function __call($method, $args) { 
     if (preg_match('#^((?:get|set))(.*)$#', $method, $match)) { 
      $property = lcfirst($match[2]); 
      $action = $match[1]; 
      if ($action === 'set') { 
       $this->$property = $args[0]; 
      } else { 
      return $this->$property; 
      } 
     } 
    } 

    public function getD() { 
     return $this->otherData['d']; 
    } 

    public function setD($value) 
    { 
     $this->otherData['d'] = $value; 
    } 
} 

$x = new Test(); 
$x->setA('a value'); 
$x->setB('b value'); 
$x->setValueForC('c value'); 
$x->setD('special value for D'); 

echo $x->getA() ."\n"; 
echo $x->getB() ."\n"; 
echo $x->getValueForC() ."\n"; 
echo $x->getD() ."\n";