PHP 构造不回显变量
PHP construct not echoing variables
我是 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;
}
}
您需要通过在代码中的某处调用 new Variable()
来实例化 class。但是,一般来说,最好不要让 class 依赖于 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();
另请注意我是如何从构造函数中提取输出的。它唯一的任务应该是将对象初始化为有效状态。处理输入或生成输出不是它的职责。
我是 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;
}
}
您需要通过在代码中的某处调用 new Variable()
来实例化 class。但是,一般来说,最好不要让 class 依赖于 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();
另请注意我是如何从构造函数中提取输出的。它唯一的任务应该是将对象初始化为有效状态。处理输入或生成输出不是它的职责。