您好,欢迎访问一九零五行业门户网

php 类中定义了一个public的方法,怎么知道这个方法是被类外调用的还是类内调用的

示例代码如下:
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; }}
其它类似信息

推荐信息