PHP: Returning a variable from an include file.

This is a quick tutorial on how to “return” variables from an included PHP file. This design can be used whenever you want to assign the return value of an included file to a variable in your main script (the main script in this case is the script that “called” your included file). In this example, I will be using two files: main.php and included_file.php

Take a look at the following code snippet:

included_file.php

This is the file that we will be including:

<?php

//Return a basic string variable.
return 'My String Variable';

Note that in the example above, I am returning a string variable. To return a variable from an included file, you MUST use the return statement.

main.php

This is our main script. This is the file that “calls” our included file:

<?php

//include our file and assign its return value to a variable
$stringVariable = include 'included_file.php';

//print it out
echo $stringVariable;

Above, we include the file included_file.php and assign its return value to a variable called $stringVariable.

If you run the code above, you’ll see that the include statement returned the string variable that we created in included_file.php

In the past, I have seen type of design being used to store and retrieve configuration values. For example: In the MVC framework Laravel, there is a config folder that contains files such as mail.php, session.php and database.php. If you open any of these files, you’ll see that each file is returning an associative array that contains configuration values.

Here is a basic example of an include file returning configuration values:

<?php

//This our database configuration file. We will call it database.php

//Return an associative array containing our database config values.
return array(
    'db_host' => 'localhost',
    'db_user' => 'root',
    'db_pass' => '',
    'db_name' => 'test'
);

Then, if we want to retrieve the configuration values above:

<?php

$databaseConfig = include 'database.php';

var_dump($databaseConfig);

If you run the code above, you will see that $databaseConfig contains the associative array that we created in database.php

Facebook Comments