我可以在每个语句的多行中编写 PHP 代码吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6699924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I write PHP code across multiple lines per statement?
提问by tim
Is it okay to write code like this, with statements spanning across multiple lines?
编写这样的代码,语句跨越多行可以吗?
$db_selected =
mysql_select_db(
'my_dbase',
mysql_connect(
'localhost',
'mysql_user',
'mysql_password'
)
);
In HTML, new lines are ignored, but in PHP I sometimes get errors. I'm not too familiar with PHP, but thought this should be just fine, no?
在 HTML 中,新行会被忽略,但在 PHP 中我有时会出错。我对 PHP 不太熟悉,但认为这应该没问题,不是吗?
回答by cwallenpoole
No, but not for why you think. The whitespace is fine, but there is an issue with that code:
不,但不是因为你为什么这么想。空格很好,但该代码存在问题:
mysql_select_db(
'my_dbase',
// don't call mysql_connect here!!!
mysql_connect(
'localhost',
'mysql_user',
'mysql_password'
)
);
MySQL connect will return FALSE on error. This means that you'll not be able to handle the mysql_error()
there ANDit will cause an error in mysql_select_db
.
MySQL 连接将在出错时返回 FALSE。这意味着您将无法处理mysql_error()
那里,并且会导致mysql_select_db
.
You're better off:
你最好:
$conn = mysql_connect(
'localhost',
'mysql_user',
'mysql_password'
) or die( mysql_error() );
mysql_select_db(
'my_dbase',
$conn // optional parameter, but useful nonetheless.
);
回答by tim
I'm gonna answer my own question: Simply tried this and on my LAMP server, the originally posted code snippet works just fine (php 5).
我要回答我自己的问题:简单地尝试这个,在我的 LAMP 服务器上,最初发布的代码片段工作得很好(php 5)。
So yes, you can separate statements including those with operators into multiple lines.
所以是的,您可以将包括带有运算符的语句在内的语句分成多行。
And the answer with the string concatenation - yes there are myriad answers on this forum already about that but I was asking about statements, not strings, which I could not find answered elsewhere.
和字符串连接的答案 - 是的,这个论坛上已经有无数关于这个的答案,但我问的是陈述,而不是字符串,我在其他地方找不到答案。
Thanks everyone! Especially Geroge Cummins.
谢谢大家!尤其是乔治·康明斯。
回答by Shaz
Yes it's okay, as long as there are no new lines after operators, such as =
, in
, ==
, etc...
是的,这没关系,只要没有新线运营后,如=
,in
,==
,等...
回答by George Cummins
Whitespace is generally ignored, so you can insert line breaks as needed. However, you need to end each statement with a semicolon (;
).
空格通常会被忽略,因此您可以根据需要插入换行符。但是,您需要以分号 ( ;
)结束每个语句。
回答by Brian Patterson
Yes, but for certain things, such as text I do something like ...
是的,但是对于某些事情,例如文本,我会做一些类似的事情......
$someText = " blah blah blah ".
"some more blah blah blah";
Hope this helps
希望这可以帮助