dongshi6529 2014-03-27 23:31
浏览 34
已采纳

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

New to OOP, the idea is to instantiate an object in a class passing two properties in the process and using a method within the class to generate a third property that i would later need to use.

Does this make sense in OOP terms? I would have thought that my dostuff method would create my thirdproperty ready for use for my next methods in the class?

Here's my code:

<?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;
?>

What am I doing wrong? My var_dump($newInstance->thirdproperty) returns Null - as initially set i suppose.... slightly confused here?!

  • 写回答

2条回答 默认 最新

  • douaoli5328 2014-03-27 23:34
    关注

    If you want thirdproperty to be set, then you need to call `dostuff'. One way to accomplish this would be to modify your constructor slightly:

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

    However, you're missing out on one of the benefits of using OOP by passing that parameter. Instead, you could rewrite dostuff as so:

    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();
    }
    

    Of course, this all depends on how you intend to use dostuff.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃