PHP构造函数不会输出变量

3

我对PHP还很陌生,仍在逐渐了解构建方式,希望能得到一些帮助!

以下代码无法输出变量 $arrivalTime 和 $hourStay:

class Variable {

public $arrivalTime;
public $hourStay;   

public function __construct() {
    $this->arrivalTime = $_POST['arrivalTime'];
    $this->hourStay = $_POST['hourStay'];

    echo $this->arrivalTime;
    echo $this->hourStay;
}
}

2
你正在实例化这个类吗? - Daan
1
new Variable();... - War10ck
你需要创建一个类的实例。 - Yuri Blanc
检查$_POST值是否已定义,例如; $this->arrivalTime = isset($_POST['arrivalTime'])? $_POST['arrivalTime'] : "没有到达时间可用"; - DFriend
2
我没有看到更大的画面,无法确定...如果您不希望类依赖于后置值,则可以像那样传递它们,或者更好地作为构造函数中的输入。 - Cosmin
显示剩余3条评论
1个回答

3

您需要实例化该类,通过在代码中的某个位置调用new Variable()。然而,一般来说最好不要让您的类依赖于post变量,而是通过构造函数将它们传递进去:

class Variable {

  public $arrivalTime;
  public $hourStay;   

  public function __construct($arrivalTime, $hourStay) {
      // TODO: Check if the values are valid, e.g.
      // $arrivalTime is a time in the future 
      // and $hourStay is an integer value > 0.
      $this->arrivalTime = $arrivalTime;
      $this->hourStay = $hourStay;
  }

  public function print() {
      echo $this->arrivalTime;
      echo $this->hourStay;
  }
}

$var = new Variable($_POST['arrivalTime'], $_POST['hourStay']);
$var->print();

此外,请注意我将输出生成过程从构造函数中移除。它的唯一任务应该是将对象初始化为有效状态。处理输入或生成输出不是它的责任。

非常感谢,这正是我在寻找的。为了单独获取每个变量,这样做是否是一个好方法?:http://pastie.org/pastes/10516156/text - Liam Macmillan
我会在构造函数中包含验证,以确保到达时间和停留时间有效,并将取货时间的计算移动到getter中:public function get_pickupTime() { return date('H:i', (strtotime($this->arrivalTime) + $this->hourStay)); } - CompuChip

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接