2 回答
TA贡献1752条经验 获得超4个赞
__get如果访问了一个类的属性但未定义,则可以使用magic方法实现此目的,该方法将被调用。在我看来,这是很棘手的,但是可以按照您的意愿来工作。
<?php
class test {
public function __construct($p1, $p2) {
$this->p1 = $p1;
$this->p2 = $p2;
}
public function __get($name) {
if ('p_max' === $name) {
return max(array($this->p1, $this->p2));
}
}
}
$test = new test(1,2);
echo $test->p_max; // Prints 2
$test->p1 = 3;
$test->p2 = 4;
echo $test->p_max; // Prints 4
这样,每次访问此属性时,都会计算出最大值。
编辑:因为__get方法将仅针对属性(在类本身中未定义)调用,所以如果在构造函数中为变量分配值或将其创建为属性,则此方法将无效。
Edit2:我想再次指出-用这种方法很难做。为了获得更清洁的方式,请遵循AbraCadaver的答案。这也是我个人的做法。
TA贡献1712条经验 获得超3个赞
您实际上并不需要使用魔术方法,只需使用一种返回计算值的方法即可:
class test{
public function __construct($p1, $p2){
$this->p1 = $p1;
$this->p2 = $p2;
}
public function p_max() {
return max($this->p1, $this->p2);
}
}
$test->p1 = 3;
$test->p2 = 4;
echo $test->p_max(); // call method
您还可以接受可选参数来p_max()设置新值并返回计算出的值:
class test{
public function __construct($p1, $p2){
$this->p1 = $p1;
$this->p2 = $p2;
}
public function p_max($p1=null, $p2=null) {
$this->p1 = $p1 ?? $this->p1;
$this->p2 = $p2 ?? $this->p2;
return max($this->p1, $this->p2);
}
}
echo $test->p_max(3, 4); // call method
还要注意,它max接受多个参数,因此您不必指定数组。
- 2 回答
- 0 关注
- 196 浏览
添加回答
举报