Is it possible to have return statements inside an included file that is inside a function in PHP?

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.

As in
function sync() {
  include_once file.php;
  echo "Test";
}

file.php:

...
return "Something";

At the moment the return something appears to break out of the include_once and not the sync function, is it possible for the included file's return to break out?

Sorry for the slightly odly worked question, hope I made it make sense.

Thanks,

Accepted Answer

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.

Written by LazyOne
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki