猿问

在PHP中动态更改属性

我对OOP有一些抽象的知识,但这是我第一次尝试用PHP编写一些OOP。我想创建一个类,该类将具有一些来自构造的属性,但有些属性会动态变化。


我对所有的术语(对象,类,方法等)有些困惑,所以我不知道确切要搜索什么。我在下面做了一个简化的例子。


这是我声明我的类的地方,它将在构造中接受2个参数并计算第三个参数,即较高的数字(请忽略我不检查类型)。


class test{

  public function __construct($p1, $p2){

    $this->p1 = $p1;

    $this->p2 = $p2;

    $this->p_max = max(array($this->p1, $this->p2));

  }

}

然后,我初始化对象并检查p_max:


$test = new test(1,2);

echo $test->p_max; // Prints 2

但是,如果我更改p1和p2,则p_max不会更改:


$test->p1 = 3;

$test->p2 = 4;

echo $test->p_max; // Prints 2 (I want 4)

我应该如何在类中定义p_max以在每次更改p1或p2时进行更新?有没有一种方法可以不将p_max转换为方法?


慕哥6287543
浏览 197回答 2
2回答

温温酱

__get如果访问了一个类的属性但未定义,则可以使用magic方法实现此目的,该方法将被调用。在我看来,这是很棘手的,但是可以按照您的意愿来工作。<?phpclass test {&nbsp; &nbsp; public function __construct($p1, $p2) {&nbsp; &nbsp; &nbsp; &nbsp; $this->p1 = $p1;&nbsp; &nbsp; &nbsp; &nbsp; $this->p2 = $p2;&nbsp; &nbsp; }&nbsp; &nbsp; public function __get($name) {&nbsp; &nbsp; &nbsp; &nbsp; if ('p_max' === $name) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return max(array($this->p1, $this->p2));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}$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的答案。这也是我个人的做法。

交互式爱情

您实际上并不需要使用魔术方法,只需使用一种返回计算值的方法即可:class test{&nbsp; public function __construct($p1, $p2){&nbsp; &nbsp; $this->p1 = $p1;&nbsp; &nbsp; $this->p2 = $p2;&nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; public function p_max() {&nbsp; &nbsp; return max($this->p1, $this->p2);&nbsp; }}$test->p1 = 3;$test->p2 = 4;echo $test->p_max(); // call method您还可以接受可选参数来p_max()设置新值并返回计算出的值:class test{&nbsp; public function __construct($p1, $p2){&nbsp; &nbsp; $this->p1 = $p1;&nbsp; &nbsp; $this->p2 = $p2;&nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; public function p_max($p1=null, $p2=null) {&nbsp; &nbsp; $this->p1 = $p1 ?? $this->p1;&nbsp; &nbsp; $this->p2 = $p2 ?? $this->p2;&nbsp; &nbsp; return max($this->p1, $this->p2);&nbsp; }}echo $test->p_max(3, 4); // call method还要注意,它max接受多个参数,因此您不必指定数组。
随时随地看视频慕课网APP
我要回答