OOP通过类中的方法设置属性?

时间:2014-03-27 23:31:45

标签: php oop properties

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-&gt; thirdproperty)返回Null - 最初设置我想......在这里稍微混淆了一些?!

2 个答案:

答案 0 :(得分:1)

如果你想设置thirdproperty,那么你需要调用`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

答案 1 :(得分:1)

你为什么不改变这个

public function __construct ($firstproperty, $secondproperty) {

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

public function __construct ($firstproperty, $secondproperty) {

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