範例程式碼如下:
class Person{ protected $name; protected $hi; protected $age; public function __construct($name, $hi, $age) { $this->name = $name; $this->hi = $hi; $this->age = $age; } public function get($propertyName, $default = null) { if (...) { // TODO **判斷如果是類外調用的**,且$propertyName === 'age' throw new \InvalidArgumentException(spintf( '%s access failed!', $propertyName )); } if (isset($this->$propertyName) && $this->$propertyName !== null) { return $this->$propertyName; } else { return $default; } } public function getAge() { return $this->get('age', 18); }}$xiaoMing = new Person('xiaoMing', 'I\'m xiaoMing', 20);$xiaoMing->get('age'); // 拋異常$xiaoMing->getAge(); // 20
現在我想解決的問題是:現在我想訪問類內部屬性統一通過get方法,在get方法裡面類內部可以訪問怎麼$name, $hi, $age三個屬性,類外部只能訪問$name, $hi這兩個屬性,如果沒有辦法那我只能判斷定義兩個方法:
protected function insideGet($propertyName, $default = null); // 提供給內部使用
public function outsideGet($propertyName, $default = null); // 提供給外部使用
請大神幫忙解決這個問題,如果有更好的法案也請告知,謝謝
回複內容:
範例程式碼如下:
class Person{ protected $name; protected $hi; protected $age; public function __construct($name, $hi, $age) { $this->name = $name; $this->hi = $hi; $this->age = $age; } public function get($propertyName, $default = null) { if (...) { // TODO **判斷如果是類外調用的**,且$propertyName === 'age' throw new \InvalidArgumentException(spintf( '%s access failed!', $propertyName )); } if (isset($this->$propertyName) && $this->$propertyName !== null) { return $this->$propertyName; } else { return $default; } } public function getAge() { return $this->get('age', 18); }}$xiaoMing = new Person('xiaoMing', 'I\'m xiaoMing', 20);$xiaoMing->get('age'); // 拋異常$xiaoMing->getAge(); // 20
現在我想解決的問題是:現在我想訪問類內部屬性統一通過get方法,在get方法裡面類內部可以訪問怎麼$name, $hi, $age三個屬性,類外部只能訪問$name, $hi這兩個屬性,如果沒有辦法那我只能判斷定義兩個方法:
protected function insideGet($propertyName, $default = null); // 提供給內部使用
public function outsideGet($propertyName, $default = null); // 提供給外部使用
請大神幫忙解決這個問題,如果有更好的法案也請告知,謝謝
不知道怎麼檢查調用者,但是通常根本不需要這樣處理。
你的邏輯思路為:使用get方法擷取屬性值,但是年齡需要特別處理,所以不能用get(age),而是應該調用特定的方法getAge。
實際上可以簡化為:使用get方法擷取屬性值,如果該屬性需要特別處理則返回指定方法的傳回值。
程式碼範例:
public function get($propertyName, $default = null) { if (method_exists($this, '_get' . $propertyName)) { $method = '_get' . $propertyName; return $this->$method($default); } if (isset($this->$propertyName) && $this->$propertyName !== null) { return $this->$propertyName; } return $default;}protected function _getAge() { if (! isset($this->age)) { $this->age = 18; } return $this->age;}
public function get($propertyName, $default = null){ if (...) { // TODO **判斷如果是類外調用的**,且$propertyName === 'age' throw new \InvalidArgumentException(spintf( '%s access failed!', $propertyName )); } return getInner($propertyName, $default);}protected function getInner($propertyName, $default = null){ if (isset($this->$propertyName) && $this->$propertyName !== null) { return $this->$propertyName; } else { return $default; }}