PHP: Return An include And Assign It To A Variable

The include statement is a simple way to include PHP code from another file.

The usage is quite simple. Just write something like this:

<?php
include 'a_file.php';

If the file is successfully included it will return a TRUE or 1. If it failes to include the file it will return a FALSE. But sometimes you may need to get the content of an included file in order to store it in an variable. Unfortunately the include statement just returns TRUE or FALSE, as mentioned above.


Advertisement

How to store an included file in an variable

There are ways to store data from an included file in an array.

Use functions

One way is to use functions in your included file. You can call them and will get a return value.

Use return

Another way is to use the return statement in your included file. Here’s a little example:

<?php
// The included file (ip.php):
$addr = $_SERVER['REMOTE_ADDR'];;
return $addr;
?>

This file will be called from within the following:

<?php
// The including file:
$ip = (include('./somewhere/ip.php'));
echo $ip;
?>

Happy coding 🙂


Advertisement
(Visited 54 times, 1 visits today)

Leave a Comment