我想知道是否可以if在使用 PHP 分配的同一语句中使用变量。
例如:
if ($start = strtotime($_POST['date']) && $start <= time()) {
$error = 'You must choose a date in the future.';
}
Run Code Online (Sandbox Code Playgroud)
该代码似乎对我不起作用,但我不明白为什么不应该这样做,因为我知道可以像这样分配变量,然后让以下变量能够访问对我来说是有意义的它。
您遇到了运算符优先级问题。&&具有比 更高的优先级=,因此它被处理为:
if ($start = (strtotime($_POST['date']) && $start <= time())) {
Run Code Online (Sandbox Code Playgroud)
$start直到&&表达式完成后才分配给,这意味着它将$start在分配之前尝试在比较中使用。并且它还为 分配了一个布尔true/false值$start,这显然没有用。
要么在赋值前后加上括号,要么使用优先级较低的and运算符:
if (($start = strtotime($_POST['date'])) && $start <= time()) {
if ($start = strtotime($_POST['date']) and $start <= time()) {
Run Code Online (Sandbox Code Playgroud)