如何在php中抑制警告消息

时间:2011-10-23 20:00:22

标签: php

我对php世界很新。我写了以下内容:

<html>
<head>
    <title>It joins simple1 and prac1 program together</title>
</head>
<body>
    <?php
        if($_POST['user'])
        {
            print "hello,";
            print $_POST['user'];
        }
        else{
        print <<<_HTML_
            <form method="post" action="$_server[PHP_SELF]">
                Your name:<input type="text" name="user">
                </br>
                <input type="submit" value="hello"> 
            </form>
        _HTML_;
        }           
    ?>
</body>
</html>  ---- line 23

获取错误消息:

Parse error: syntax error, unexpected $end in C:\wamp\www\php_practice\simple2.php on line 23

我删除了所有的html标签,并保留了有效的php标签:

<?php
// Print a greeting if the form was submitted
if ($_POST['user']) {
print "Hello, ";
// Print what was submitted in the form parameter called 'user'
print $_POST['user'];
print "!";
} else {
// Otherwise, print the form
print <<<_HTML_
<form method="post" action="$_SERVER[PHP_SELF]">
Your Name: <input type="text" name="user">
<br/>
<input type="submit" value="Say Hello">
</form>
_HTML_;
}
?>

输出:提供正确的输出,但带有警告

Notice: Undefined index: user in C:\wamp\www\php_practice\test.php on line 3
  1. 为什么不能使用上一个案例?出了什么问题?

  2. 如何在第二个代码中删除或静音警告消息。它在浏览器中看起来很糟糕。

2 个答案:

答案 0 :(得分:7)

解析错误的原因:

HEREDOC语句的结束必须发生在行的开头,之前或之后没有空格。您的_HTML缩进到与其余代码相同的级别,但它必须出现在该行的第一个字符位置。

    _HTML_;

// Should be
_HTML_;

undefined index警告的原因:

要测试是否设置了$_POST['user'],请使用isset()。这将解决您的undefined index错误。

if(isset($_POST['user']))

更新:undefined variable _server通知的原因:

在HEREDOC或双引号字符串中,您需要在{}中包装复杂变量(数组,对象)。另外,在PHP_SELF附近加上引号。

<form method="post" action="{$_SERVER['PHP_SELF']}">

答案 1 :(得分:0)

您可以使用函数名之前的@来抑制PHP中的错误(在这种情况下不起作用)或将error_reporting设置为不同的值(http://www.php.net/manual/en/function.error-reporting.php)。

但你应该修复警告的来源,而不是压制它。在这种情况下, HTML ;

之前有空格