Use PHP include with variable concatenation

Hi everyone,

this is what I’m trying to do:

$content .= ‘include (“inc/foo.php”)’;

How can I get this to work? Thank you for any help.

remove the single quotes. currently you append a string not an include.

Well, you could use file_get_contents to read the contents of the file. But if you wanted the capture the outout of the file, as it executes, you could use output buffering:

ob_flush();//flush the current buffer content to output
include ("inc/foo.php");//does some output, via the buffer
$content = ob_get_clean();//gets the buffer content and wipes it clean, ready for subsequent output

However I should point out that there are surely much better ways to do what you’re trying to do. Rather than bending the language to suit a bad practice, use the best practices of the language. If you have some data in an include, set it to a variable, so that the executing code has access to the variable. Even that is a bit 2003, but without knowing more about what is going on it’s hard to advise. But if you’re dead set on outputting from your include, and capturing that as a string, then the above code will work.

Removing the quotes will assign to $content the return value of the include() function, which is only 1 or 0, not the output of the include itself.

Removing the quotes will assign to $content the return value of the include() function, which is only 1 or 0

or whatever you put in the included file’s return statement.

If the current script file was included or required, then control is passed back to the calling file. Furthermore, if the current script file was included, then the value given to return will be returned as the value of the include call.

I stand corrected. I had no idea there was such thing as issuing a return from the global scope of an included file. Sounds like a pretty mental thing to do, but it would work.

it’s not mental. you can use it neatly for defining closed-scope* local configuration without the need to define constants.

    • otherwise the config variables would leak into the global scope.

Hi Dormilich and hessodreamy,

thanks a lot for both of your help. I got the include working.