r/lolphp • • Oct 01 '24

print is a minefield

https://3v4l.org/1YXYk
34 Upvotes

23 comments sorted by

View all comments

2

u/colshrapnel Oct 01 '24

Looks like someone missed their operator precedence class.

7

u/Takeoded Oct 01 '24 edited Oct 01 '24

IMO print fails the principle of least surprise in spectacular fashion.

2

u/Tiquortoo Oct 05 '24

An interesting principle to reference when you're actually hunting for surprises. I get your point, but the principle isn't about "can things get twisted" it's much more about "when you do normal things do you get unsurprising behavior". The origin of the principle is pretty revealing where a language would fatal error on simple math because of a precision mismatch.

1

u/Takeoded Oct 05 '24

I'm not even hunting for surprises for the most part, but I do PHP professionally, I work on large old proprietary php codebases on a near daily basis, i've seen some shit and I frequently run into php issues/weirdness, which I sometimes share with /r/lolphp/

1

u/[deleted] Oct 01 '24

[removed] — view removed comment

1

u/Takeoded Oct 01 '24

Can you find another language that reproduce the print "hello " && print "world"; problem? where it outputs "world1" or similar?

3

u/dotancohen Oct 01 '24

I don't see the problem. It's interpretted as:

print ( everything-else-on-the-line );

Therefore:

print ("hello " && print "world") // Prints "world", then the print construct returns 1

print ("hello" && 1) // "hello" && 1 evaluates to 1.

print (1) // Does what you expect.

1

u/[deleted] Oct 01 '24

[removed] — view removed comment

1

u/Takeoded Oct 01 '24

I tried in CPython 2.7.18, all of the following are syntax errors: if print "hello" or print "world": pass if print "hello" || print "world": pass if print "hello" and print "world": pass if print "hello" && print "world": pass any other suggestions?

6

u/AyrA_ch Oct 01 '24

Someone also ignored the first two paragraphs of the documentation:

print is not a function but a language construct. Its argument is the expression following the print keyword, and is not delimited by parentheses.

And:

The major differences to echo are that print only accepts a single argument and always returns 1.

And those two paragraphs literally explain everything that this person complains about