开发者

PHP: whitespaces that do matter [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 12 years ago.

Whitespaces are generally ignored in PHP syntax, but there are several places where you cannot put them without affecting the sense (and the result).

One example is:

$a = 5.5;    // five and a half开发者_开发问答 (float)
$b = 5 . 5;  // "55" (string)

Do you know of any other examples?

The question is not about why is that working this way, but what are situations, when omitting or placing whitespace changes the program, but both versions are syntactically correct.


That one had me going berserk. I present the whitespace of doom:

function foo() {
   print "I'm foo.";
}

if (something()) {
    foo();
}

When executing, the error was:

Fatal error: Call to undefined function foo() on line 6

After an hour or so, I found out, the error message actually said:

Fatal error: Call to undefined function  foo() on line 6

Notice the double spaces:

function  foo()

It turned out that by copy/pasting the above code (formatted with highlight_string), a non-breaking space  , or 0xA0 is acceptable in identifiers, so the function call was to 0xA0foo() instead of foo().


You can't put spaces in the middle of a number! Gosh!

$x = 10 3.5; //syntax error

If you put a space in the middle of an operator, it's no longer that operator!!

if (true & & true) echo 'true'; //syntax error

If I put a space in the middle of my string, it's not the same string!

echo "Hel lo World"; //does NOT print "Hello World"!

Sorry, but this question is ridiculous, since of course you can't throw spaces in the middle of tokens without either changing behavior or breaking code. Just the same as in virtually every other programming and written language.

5.5 is a number, 5 . 5 is a string because . is the string concatenation operator. That's just the language's syntax.


In your example, you are breaking a single lexical token in two (a bit like breaking function into func tion, whitespace is indeed not ignored in that way). This is not really interesting, you could come up with many examples when things break that way, the only interesting task is to try to find an example which works (i.e. not a syntax error), but differently, e.g.:

$a = $x++ + $y;   // x is incremented
$b = $x+ + + $y;  // x is not incremented
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜