2 回答

TA貢獻(xiàn)1752條經(jīng)驗(yàn) 獲得超4個(gè)贊
__get如果訪問了一個(gè)類的屬性但未定義,則可以使用magic方法實(shí)現(xiàn)此目的,該方法將被調(diào)用。在我看來,這是很棘手的,但是可以按照您的意愿來工作。
<?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
這樣,每次訪問此屬性時(shí),都會計(jì)算出最大值。
編輯:因?yàn)開_get方法將僅針對屬性(在類本身中未定義)調(diào)用,所以如果在構(gòu)造函數(shù)中為變量分配值或?qū)⑵鋭?chuàng)建為屬性,則此方法將無效。
Edit2:我想再次指出-用這種方法很難做。為了獲得更清潔的方式,請遵循AbraCadaver的答案。這也是我個(gè)人的做法。

TA貢獻(xiàn)1712條經(jīng)驗(yàn) 獲得超3個(gè)贊
您實(shí)際上并不需要使用魔術(shù)方法,只需使用一種返回計(jì)算值的方法即可:
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
您還可以接受可選參數(shù)來p_max()設(shè)置新值并返回計(jì)算出的值:
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接受多個(gè)參數(shù),因此您不必指定數(shù)組。
- 2 回答
- 0 關(guān)注
- 216 瀏覽
添加回答
舉報(bào)