How to pass the require_once output to a variable?

file_get_contents will get the content of the file. If it's on the same server and referenced by path (rather than url), this will get the content of test.php. If it's remote or referenced by url, it will get the output of the script.


“The result” presumably is a string output?

In that case you can use ob_start to buffer said output:

ob_start();
require_once('test.php');
$test = ob_get_contents();

EDIT From the edited question it looks rather like you want to have a function inside the included file. In any case, this would probably be the (much!) cleaner solution:

<?php // test.php:

function some_function() {
    // Do something.
    return 'some result';
}

?>

<?php // Main file:

require_once('test.php');

$result = test_function(); // Calls the function defined in test.php.
…
?>

Is it possible?

Yes, but you need to do an explicit return in the required file:

//test.php

<? $result = "Hello, world!"; 
  return $result;
?>

//index.php

$test = require_once('test.php');  // Will contain "Hello, world!"

This is rarely useful - check Konrad's output buffer based answer, or adam's file_get_contents one - they are probably better suited to what you want.

Tags:

Php

File