【问题标题】:OOP setting a property through a method within the class?OOP 通过类中的方法设置属性?
【发布时间】:2014-03-27 23:31:44
【问题描述】:

OOP 的新手,想法是在一个类中实例化一个对象,在进程中传递两个属性,并使用类中的一个方法来生成我以后需要使用的第三个属性。

这在 OOP 方面有意义吗?我会认为我的 dostuff 方法会创建我的第三个属性,以供课堂中的下一个方法使用?

这是我的代码:

<?php
class Nameofclass {

public $firstproperty = '';
public $secondproperty ='';
public $thirdproperty ='';


public function __construct ($firstproperty, $secondproperty) {

$this->firstproperty = $firstproperty;
$this->secondproperty = $secondproperty;
}

public function dostuff($firstproperty) {
do a lot of clever stuff here to calculate a $value;
$this->thirdproperty = $value
}

}
$newInstance = new Nameofclass('firstproperty', 'secondproperty');
echo $newInstance->thirdproperty;
?>

我做错了什么?我的 var_dump($newInstance->thirdproperty) 返回 Null - 我想最初设置的......这里有点困惑?!

【问题讨论】:

  • 如果thirdproperty的值仅由dostuff()设置,则需要调用dostuff()...除非在构造函数中调用,否则不会调用自己
  • 谢谢马克!那我可以在构造函数中调用 dostuff() 吗?
  • 你没有理由不这样做

标签: php oop properties


【解决方案1】:

如果你想设置第三个属性,那么你需要调用`dostuff'。实现此目的的一种方法是稍微修改您的构造函数:

public function __construct ($firstproperty, $secondproperty) {
    $this->firstproperty = $firstproperty;
    $this->secondproperty = $secondproperty;
    $this->dostuff($firstproperty);
}

但是,您错过了通过传递该参数来使用 OOP 的好处之一。相反,您可以这样重写 dostuff:

public function dostuff() {
    // use $this->firstproperty here, since youve already set it instead of passing it into the function
    do a lot of clever stuff here to calculate a $value;
    $this->thirdproperty = $value;
 }

 // Then, your call to dostuff in your constructor could look like this (without the parameter)

public function __construct ($firstproperty, $secondproperty) {
    $this->firstproperty = $firstproperty;
    $this->secondproperty = $secondproperty;
    $this->dostuff();
}

当然,这一切都取决于你打算如何使用dostuff。

【讨论】:

  • 感谢 Cale_b!工作正常!在这个构造函数上还有很多东西要学!
  • @Guillaume 或者只是为了了解如果您不调用函数将不会被调用:)
  • @RoyalBg 确实!现在 __construct 调用对我来说应该更容易!!! ;-)
【解决方案2】:

你为什么不改变这个

public function __construct ($firstproperty, $secondproperty) {

$this->firstproperty = $firstproperty;
$this->secondproperty = $secondproperty;
}

到

public function __construct ($firstproperty, $secondproperty) {

$this->firstproperty = $firstproperty;
$this->secondproperty = $secondproperty;
$this->doStuff()
}

【讨论】:

  • 感谢塞菲多!如前所述,OOP 的新手!很简单!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
相关资源
最近更新 更多