views:

57

answers:

2

I have the following code:

if (include_once(dirname(__FILE__).'/file.php')
    || include_once(dirname(__FILE__).'/local/file.php')
    )
{

This causes an error because PHP tries to include "1" (presumably dirname(__FILE__).'/file.php' || dirname(__FILE__).'/local/file.php')

Commenting out the second line makes this work as intended, other than the fact it won't use the second file. Do I really need to use elseif and code duplication here, or is there a way to get this working?

$ php --version
PHP 5.2.6-3ubuntu4.2 with Suhosin-Patch 0.9.6.2 (cli) (built: Aug 21 2009 19:14:44)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies

A: 

Try using parentheses to subdue the operator precedence.

if ( (include_once('xml.php')) || (include_once('xml.php')) ) {
    echo 'bah';
}
meder
+4  A: 

Group the include statements:

if ( (include_once dirname(__FILE__).'/file.php')
      ||
     (include_once dirname(__FILE__).'/local/file.php')
   )

See example #4 in the manual page:

<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
    echo 'OK';
}

// works
if ((include 'vars.php') == 'OK') {
    echo 'OK';
}
?>
Ionuț G. Stan
This is... counter-intuitive to say the least. A thousand curses on PHP's 'language constructs'.
Matthew Scharley
Indeed, but that's one of the main traits of PHP :). Anyway, I'd just assign the return value of the statements to some temp variables, and use those inside the `if` test.
Ionuț G. Stan
Alright, I have to ask: Which is one of the main traits of PHP? Being counter-intuitive, or using language constructs instead of actual functions?
Matthew Scharley
Also, the main reason I chose to do it this way was because I only wanted the first of the two pages to run (if both were actually there)
Matthew Scharley
The trait would be, indeed, that it is counter-intuitive, or rather inconsistent.
Ionuț G. Stan