面向对象的php与类混淆以及如何调用它们

时间:2013-03-05 02:22:37

标签: php oop class

您好我的代码非常简单,我试图使用面向对象的方法作为学习练习但是识别类和实现它有点令人困惑

所以在我目前的程序中,我有一个函数,我在计算某个任务在一个月内花费了多少时间以及剩余多少时间:

例如function timeremaining ($dob, $task1start=null, $task1end=null, $item2start=null, $task2end=null)

如果我在面向对象编程中尝试做类似的事情,我想我会用这样的东西但不确定:

class person extends task { 
  public $age; 
  public $name; 
  public $phoneno ;
  public $totaltimethismonth;
} 

class task extends time{ 
  public $name ; 
  public $timefrom; 
  public $timeto;

  public function getDuration($name,$timefrom,$timeto)
  {
    list($hours, $minutes) = explode(':', $timefrom);
    $startTimestamp = mktime($hours, $minutes);

    list($hours, $minutes) = explode(':', $timeto);
    $endTimestamp = mktime($hours, $minutes);

    $seconds = $endTimestamp - $startTimestamp;
    $totaldurationinseconds=$totalsecondsinday - $seconds;
    return $totaldurationinseconds;
  }
} 

class time { 
  public $hours ; 
  public $minutes; 
  public $seconds;
  //not sure if time should be used?
}

$newperson = new person;

$duration=$newperson->getDuration("gardening","10:00","17:00");
$totaltime=$newperson->totaltimethismonth;
echo "remaing time this month is $totaltime-$duration;

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

如果没有更详细地描述您希望应用程序执行的操作,这有点难以回答。但我可以指出一些问题。

您错误地使用了继承。继承意味着“是一种”关系。任务不是时间,人不是任务。相反,任务有时间,人有任务。 “有一个”意味着构成。

不确定为什么getDuration正在接受争论。你已经有时间在你的对象中,所以可以

public function getDuration() {
    $duration = $this->timeFrom ... $this->timeTo ...
    return $duration;
}
然后,Person类可以有一个循环遍历任务字段的getTotalTask​​Time方法,并将你从$ task-> getDuration()获得的所有值相加。

并且,您可能希望将您的字段设为私有或受保护。它们可以通过构造函数设置。并通过吸气剂获得。如果你需要能够修改,你可以添加setter(虽然你失去了不变的不错的属性)