我是用户,是重定向页面的头函数。php中的头函数前面不允许有空格。我在页面上有一些函数,我想知道函数之间的部分是否被视为空白。
我必须这样做吗:
function nil(){
statement
}
或者我可以这样做吗:
function nil(){
Is this considered space?
statement
is this considered space?
}
任何封装在<?php
和?>
中的内容都不会发送到浏览器,而是发送到PHP解析器+解释器。解析程序将忽略所有空白。
这些空间不需要担心。您只需要担心实际发送到浏览器的空间(或发送到浏览器中的任何其他实际输出)。php代码本身实际上并没有发送到浏览器。只有php可以发送的东西(例如,使用echo
),或者如果您脱离php,或者使用header()
发送其他头,等等
=== beginning of file ===
<-- whitespace
<-- whitespace
<-- whitespace
<?php <-- not whitespace
for ($c =0; <-- not whitespace
<-- not whitespace
<-- not whitespace
$c<10; <-- not whitespace
<-- not whitespace
<-- not whitespace
$c++ <-- not whitespace
) <-- not whitespace
<-- not whitespace
{ <-- not whitespace
?> <-- not whitespace (but there could be trailing whitespace)
<p> <-- whitespace/output
<?php <-- not whitespace
echo $c; <-- not whitespace. HOWEVER, you ARE outputting something
?> <-- not whitespace (but there could be trailing whitespace)
</p> <-- whitespace/output
<?php <-- there is leading whitespace
if ($c==20) <-- not whitespace
<-- not whitespace
{ <-- not whitespace
echo 'twenty!'; <-- not whitespace. also, even though an echo would output, the condition would never be true so it is never actually output
} <-- not whitespace
} <-- not whitespace
header( <-- not whitespace
'Content-type: application/pdf' <-- not whitespace
); <-- not whitespace. anything after this doesn't matter because header is sent
?> hello! <-- output. doesn't matter, header already sent
<div> <-- output. doesn't matter, header already sent
blah <-- output. doesn't matter, header already sent
</div> <-- output. doesn't matter, header already sent
=== end of file ===
好吧,所以在现实中,希望你不会把代码写得这么难看,但这应该说明要点。尽管实际上有很多空白,但关键是在执行php代码的上下文中有空白。空白不会被发送到浏览器,因为php代码不会被发送给浏览器。因此,尽管您在代码中看到了很多空白,但我只标记了实际发送到浏览器的内容。但这里的要点是,它不仅仅是空白——它是在标头之前发送到浏览器的任何内容。
标头信息必须位于任何其他输出之前。如果您的代码在发送头之前输出了任何内容,然后您尝试发送头(这还包括尝试启动会话或编写cookie),php将向您发出警告。您甚至可能看不到它,这取决于您的错误级别设置。php不会直接崩溃,因为它并不真正关心头——这是浏览器需要解决的问题。但是,如果您试图在发送输出后发送标头,浏览器将忽略它。间接地您的php脚本可能会失败,如果它取决于某些事情(例如,如果您正试图启动会话并读取会话vars,但您在session_start()
调用之前输出了一些内容)。
头之前的输出是发送的数据,而不是键入到文件中。所以…
无效
<?php
function blah() {
echo "some output";
}
blah();
header(...);
?>
有效
<?php
function blah() {
echo "some output";
}
header(...);
blah();
?>
也是无效的
<?php
$var1 = "zzz";
?>
<?php
header(...);
这是无效的,因为在调用头之前,两个PHP块之间的空间会输出HTML。
如果最后一个没有意义,我可以澄清。