Php OOP通过类中的方法设置属性?
对于OOP来说,这个想法是在一个类中实例化一个对象,在这个过程中传递两个属性,并在类中使用一个方法来生成我以后需要使用的第三个属性 这在OOP术语中有意义吗?我本以为我的dostuff方法会创建我的第三十个属性,以便在类中的下一个方法中使用 这是我的密码:Php OOP通过类中的方法设置属性?,php,oop,properties,Php,Oop,Properties,对于OOP来说,这个想法是在一个类中实例化一个对象,在这个过程中传递两个属性,并在类中使用一个方法来生成我以后需要使用的第三个属性 这在OOP术语中有意义吗?我本以为我的dostuff方法会创建我的第三十个属性,以便在类中的下一个方法中使用 这是我的密码: <?php class Nameofclass { public $firstproperty = ''; public $secondproperty =''; public $thirdproperty =''; public
<?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'。实现这一点的一种方法是稍微修改构造函数:
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
为什么不更改此选项
public function __construct ($firstproperty, $secondproperty) {
$this->firstproperty = $firstproperty;
$this->secondproperty = $secondproperty;
}
到
如果
thirdproperty
的值仅由dostuff()
设置,则需要调用dostuff()
。。。除非你在构造函数中调用它,否则它不会调用它自己谢谢马克!那么,我可以在构造函数中调用dostuff()吗?没有理由不使用hanks Sephedo!如前所述,新手到OOP!非常简单!谢谢你!很好!在这个构造函数上还有很多东西需要学习,或者看起来是这样@Guillaume或只是为了了解如果不调用函数,函数将不会被调用:)@RoyalBg真的!现在_构造调用对我来说应该更容易了!!!;-)
public function __construct ($firstproperty, $secondproperty) {
$this->firstproperty = $firstproperty;
$this->secondproperty = $secondproperty;
$this->doStuff()
}