这个T_IF错误是什么意思?

时间:2011-09-08 21:50:25

标签: php parsing

<?php
$to = "service@mysite.no";
$subject = "Reparasjon av " . $_REQUEST['type'] . " fra mysite.no";
$types = if(!empty($_REQUEST['type'])) {echo($_REQUEST['type'] . ". ");};
$reps = if(!empty($_REQUEST['rep'])) {echo($_REQUEST['rep']);};
$message =  $types . . $reps . "\n\nKommentarer:\n" . $_REQUEST['kommentarer'] . "\n\nFra:\n" . $_REQUEST['navn'] . "\nTelefon: " . $_REQUEST['telefon'] . "\nEmail: " . $_REQUEST['email'] . "\nBosted: " . $_REQUEST['bosted'];
$headers =  "From: " . $_REQUEST['email'] . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/plain; charset=UTF-8' . "\r\n";
if (mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $headers)) {
   header( 'Location: http://www.mysite.no/' );
  } else {
   header( 'Location: http://www.mysite.no/' );
  }
?>

它说第4行有一个T_IF错误。问题是什么?

5 个答案:

答案 0 :(得分:3)

你不能在那里使用if,这是一个语法错误。技术上if是一个陈述,而不是表达。这意味着您无法在$types = if (...)等作业中使用它。

答案 1 :(得分:2)

if()是一种语言结构,而不是一种功能。它不返回任何内容,也不能分配给变量。

$types = if(!empty($_REQUEST['type'])) {echo($_REQUEST['type'] . ". ");};
^^^^^^^^--- not allowed

尝试:

if (!empty($_REQUEST['type']) {
   $types = $_REQUEST['type'];
}

同样,echo会导致直接输出到客户端。它不会“返回”任何可以分配的内容。

答案 2 :(得分:1)

IF语句不返回值,因此将其赋值给变量什么也不做(甚至可能导致错误!)从if语句的末尾开始分号。

试试这个:

if (!empty($some_variable)) {
  $my_var = $some_variable;
}

答案 3 :(得分:0)

我能看到的第一件事是在行$message = …中有一个双连接运算符,这显然是一个语法错误。应该(并且应该使用转义输出):

$message =  $types . $reps . "\n\nKommentarer:\n" . $_REQUEST['kommentarer'] . "\n\nFra:\n" . $_REQUEST['navn'] . "\nTelefon: " . $_REQUEST['telefon'] . "\nEmail: " . $_REQUEST['email'] . "\nBosted: " . $_REQUEST['bosted'];

PS。上帝,这段代码太错了(仍然没有逃避/清理)......

<?php
$to = "service@mysite.no";
$subject = "Reparasjon av " . $_REQUEST['type'] . " fra mysite.no";
$types = !empty($_REQUEST['type']) ? $_REQUEST['type'] . ". " : '';
$reps = !empty($_REQUEST['rep']) ? $_REQUEST['rep'] : '' ;
$message =  $types . $reps . "\n\nKommentarer:\n" . $_REQUEST['kommentarer'] . "\n\nFra:\n" . $_REQUEST['navn'] . "\nTelefon: " . $_REQUEST['telefon'] . "\nEmail: " . $_REQUEST['email'] . "\nBosted: " . $_REQUEST['bosted'];
$headers =  "From: " . $_REQUEST['email'] . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/plain; charset=UTF-8' . "\r\n";
if (mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $headers)) {
   header( 'Location: http://www.mysite.no/' );
  } else {
   header( 'Location: http://www.mysite.no/' );
  }
?>

答案 4 :(得分:0)

$types = if(!empty($_REQUEST['type'])) {echo($_REQUEST['type'] . ". ");};
$reps = if(!empty($_REQUEST['rep'])) {echo($_REQUEST['rep']);}; 

无效。 if语句不是PHP中的表达式;它们不会计算为可以赋给变量的值。你也没有从if“回归”任何东西; echo写入屏幕,它不会将if语句中的值“回显”到调用范围。

您需要以下内容:

if(!empty($_REQUEST['type'])) {
  $types = ($_REQUEST['type'] . ". ");
}
相关问题