Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should require_once "some file.php" ; appear anywhere but the top of the file?

Tags:

php

Is the following example appropriate for PHP's require_once construct?

function foo( $param )
{
    require_once "my_file.php" ;
    //
    // do something here
}

Or is it more appropriate to only have require_once constructs at the beginning of the file?

Even though the file being included is useful only in the context of the function, is it not better to have includes at the top for readability and maintainability?

like image 992
Misha M Avatar asked Nov 03 '09 19:11

Misha M


4 Answers

It comes down to a matter of coding style and opinion. Personally I keep all my require_once statements at the very top of my files so I can easily see which files are included where, nothing worse then some buried include messing with your scripts. However, if you have several large required scripts that are only required for certain functions, then putting the require_once inside a function would be OK from a performance stand-point, just make sure to put a note at the top of the page.

<?php
//require_once "my_file.php" (see function foo)

function foo($param) {
  require_once "my_file.php";
}
like image 117
TJ L Avatar answered Nov 11 '22 14:11

TJ L


This is something of a religious debate.

PROS for require and include statements at the top of the file:

  1. dependencies are clearly documented in a consistent reliable place.

  2. increased readability/maintainability

  3. OP code caching is simpler (although you could argue that this doesn't affect the developer directly)

CONS for require and include statements at the top of the file:

  1. If you're doing some kind of dynamic runtime including (such as with __autoload()), a hardcoded statement at the top of the file is impossible.

  2. If only one execution path in the code uses an include, having it included every time, unconditionally is a waste of resources.

  3. long list of include or require statement is just noise the developer must scroll past when editing a file. Of course, a long list of dependencies can be viewed as a sign that the code should be broken up into smaller more focused pieces, so maybe you could spin this one as a PRO because it makes a code smell stand out.

like image 25
Asaph Avatar answered Nov 11 '22 13:11

Asaph


If you don't want to load a file unless it's needed, look into autoloading - on newer PHP via spl_autoload_register().

like image 3
gnud Avatar answered Nov 11 '22 14:11

gnud


Maybe you only need the included file in certain cases, and you'd like to avoid including it if you don't need it at all, if it's a big file. So, I guess you could go for a require_once only in one branch of an if - else statement.

like image 1
luvieere Avatar answered Nov 11 '22 13:11

luvieere