PHP include/require within a function PHP include/require within a function php php

PHP include/require within a function


You can return data from included file into calling file via return statement.

include.php

return array("code" => "007", "name => "James Bond");

file.php

$result = include_once "include.php";var_dump("result);

But you cannot call return $something; and have it as return statement within calling script. return works only within current scope.

EDIT:

I am looking to do this as I have lots of functions in separate files and they all have a large chunk of shared code at the top.

In this case why don't you put this "shared code" into separate functions instead -- that will do the job nicely as one of the purposes of having functions is to reuse your code in different places without writing it again.


return will not work, but you can use the output buffer if you are trying to echo some stuff in your include file and return it somewhere else;

function sync() {  ob_start();  include "file.php";  $output = ob_get_clean();// now what ever you echoed in the file.php is inside the output variable  return $output;}


I don't think it works like that. The include does not simply put the code in place, it also evaluates it. So the return means that your 'include' function call will return the value.

see also the part in the manual about this:

Handling Returns: It is possible to execute a return() statement inside an included file in order to terminate processing in that file and return to the script which called it.

The return statement returns the included file, and does not insert a "return" statement.

The manual has an example (example #5) that shows what 'return' does:

Simplified example:

return.php

<?php  $var = 'PHP';return $var;?>testreturns.php<?php   $foo = include 'return.php';echo $foo; // prints 'PHP'?>