6

Just curious...when writing a require/include statement, what do you prefer as better practice?

require('filename.php');

or

require 'filename.php';

Thanks!

1 Answer 1

9

Always the latter - the same applies to echo, print and other language constructs, too. Never add additional parenthesis after language constructs!

The reason is simple: Using parenthesis makes you believe that require is a function - which it is not! For example:

if (require('file.php') == false) {
    // do stuff
}

You - and probably even most of the senior PHP developers - would say that this compares the return value of the require. But it does not! PHP interprets this as:

if (require (('file.php') == false)) {
    // do stuff
}

which is:

if (require '') {
    // do stuff
}

If you use parenthesis with language constructs you could as well write:

require(((((((((((((((((((('file.php'))))))))))))))))))))

Or would you ever write:

array(('hi'));

That's just as much the same nonsense.

Sign up to request clarification or add additional context in comments.

3 Comments

"Never use parenthesis with language constructs". So you never use array or exit with a parameter? This is really an operator precedence issue, and a fairly contrived one at that. There is no suggestion in the question.of checking a non-existent return value. And if you do write require('file.php') == false, you get an immediate fatal error. So there's no possibility of subtle bugs.
@Metthew: With array the parenthesis are part of the construct. With require they are not. You cannot omit them.
Thanks nikic! For almost 2 years now, I'm using require('filename.php'), until I bump into a code with a require 'filename.php' construction...and got curious... Thanks for your explanation! :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.