1

Is there a way to perform double require_once statement where the second one as a fallback if the first one fails?

For example: I can do this

mysql_query() or die("Boo");

Could I do:

require_once('filename') or require_once('../filename');

If one fails it reverts to the other?

Gumbo
  • 643,351
  • 109
  • 780
  • 844
Angel.King.47
  • 7,922
  • 14
  • 60
  • 85

2 Answers2

6

You can't do this because of a weird little quirk in PHP. require_once() is a language construct, not a function. It will interpret the whole line as the argument:

(('filename') or require_once('../filename'))

(added braces for clarity) the result of this operation is 1.

Use is_readable() instead.

if (is_readable($filename)) 
  require_once($filename); 
    else require_once("../$filename");

or a shorter version that should work:

require_once(is_readable($filename) ? $filename : "../$filename");
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • I will Acecpt your answer, asks me to wait 9 minutes :D. Another way i did get around this is `require_once('/var/www/html/filename')` by giving the look up to start from root it dosent matter where the file is. This is for linux only. :D – Angel.King.47 Nov 03 '10 at 11:21
2

@Pekka is correct. I'd add something else though, that might get rid of the issue entirely. If you have files in several different places, you can edit the include paths so that require() and include() look in a variety of places. See set_include_path()

The example in the manual adds a new path to the existing include path:

$path = '/usr/lib/pear';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
dnagirl
  • 20,196
  • 13
  • 80
  • 123