2

我是 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;
}
}
4

1 回答 1

2

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

还要注意我是如何从构造函数中生成输出的。它的唯一任务应该是将对象初始化为有效状态。处理输入或生成输出不是它的责任。

于 2015-10-29T15:31:08.650 回答