Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP require/include coding practices

Tags:

php

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

require('filename.php');

or

require 'filename.php';

Thanks!

like image 742
Woppi Avatar asked Nov 21 '10 11:11

Woppi


People also ask

What does PHP require?

The Require() function is also used to put data of one PHP file to another PHP file. If there are any errors then the require() function produces a warning and a fatal error and stops the execution of the script i.e. the script will continue to execute.

Can you include HTML in PHP?

While HTML and PHP are two separate programming languages, you might want to use both of them on the same page to take advantage of what they both offer. With one or both of these methods, you can easily embed HTML code in your PHP pages to format them better and make them more user-friendly.

What is require once in PHP?

The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.

What is difference between require and require_once in PHP?

The require() function is used to include a PHP file into another irrespective of whether the file is included before or not. The require_once() will first check whether a file is already included or not and if it is already included then it will not include it again.


1 Answers

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.

like image 126
NikiC Avatar answered Oct 08 '22 16:10

NikiC