I want to require/include a file and retrieve its contents into a variable.
test.php
<?php
echo "seconds passed since 01-01-1970 00:00 GMT is ".time();
?>
index.php
<?php
$test=require("test.php");
echo "the content of test.php is:<hr>".$test;
?>
Like file_get_contents()
but than it should still execute the PHP code.
Is this possible?
Use require when the file is required by the application. Use include when the file is not required and application should continue when file is not found.
These functions are the same if but they have one difference. The difference is that the include() function produces a warning, but the script will continue execution, while the require() function produces a warning and a fatal error i.e. the script will not continue execution.
If your included file returned a variable...
<?php
return 'abc';
...then you can assign it to a variable like so...
$abc = include 'include.php';
Otherwise, use output buffering.
ob_start();
include 'include.php';
$buffer = ob_get_clean();
I've also had this issue once, try something like
<?php
function requireToVar($file){
ob_start();
require($file);
return ob_get_clean();
}
$test=requireToVar($test);
?>
You can write in the included file:
<?php
return 'seconds etc.';
And in the file from which you are including:
<?php
$text = include('file.php'); // just assigns value returned in file
In PHP/7 you can use a self-invoking anonymous function to accomplish simple encapsulation and prevent global scope from polluting with random global variables:
return (function () {
// Local variables (not exported)
$current_time = time();
$reference_time = '01-01-1970 00:00';
return "seconds passed since $reference_time GMT is $current_time";
})();
An alternative syntax for PHP/5.3+ would be:
return call_user_func(function(){
// Local variables (not exported)
$current_time = time();
$reference_time = '01-01-1970 00:00';
return "seconds passed since $reference_time GMT is $current_time";
});
You can then choose the variable name as usual:
$banner = require 'test.php';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With