开发者

Is it possible to disjunct two require_once statements with OR operator to use the latter as fallback?

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_o开发者_运维知识库nce('filename') or require_once('../filename');

If one fails it reverts to the other?


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 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜