Can I write PHP code in a few lines per statement?

Is it possible to write such code when operators occupy several lines?

$db_selected = mysql_select_db( 'my_dbase', mysql_connect( 'localhost', 'mysql_user', 'mysql_password' ) ); 

In HTML, newlines are ignored, but in PHP I sometimes get errors. I'm not too familiar with PHP, but thought everything should be fine, no?

+7
source share
5 answers

No, but not because of why you think. Spaces are ok, but the problem with this code is:

 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 will not be able to handle mysql_error() there. And this will result in an error in mysql_select_db .

Do you feel better:

 $conn = mysql_connect( 'localhost', 'mysql_user', 'mysql_password' ) or die( mysql_error() ); mysql_select_db( 'my_dbase', $conn // optional parameter, but useful nonetheless. ); 
+9
source

I will answer my question: I just tried it on my LAMP server, the initially published code fragment works just fine (php 5).

So, yes, you can split statements, including statements, into several lines.

And the answer with string concatenation - yes, there are many answers on this forum already about this, but I asked about operators, not strings, which I could not find elsewhere.

Thanks everyone! Especially Hero Cummins.

+7
source

Yes, but for some things, such as text, I am doing something like ...

 $someText = " blah blah blah ". "some more blah blah blah"; 

Hope this helps

+2
source

Yes, everything is fine if there are no new lines after operators such as = , in , == , etc.

+2
source

Spaces are usually ignored, so you can insert line breaks as needed. However, you need to end each statement with a semicolon ( ; ).

+1
source

All Articles