tags:

views:

54

answers:

4

I want to call require_once("test.php") but not display result and save it into variable like this:

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

//some operations like $test = preg_replace(…);

echo $test;

Is it possible?

………………………

Thank you guys! :)

Solution:

test.php

<?php
$var = '/img/hello.jpg';

$res = <<<test

<style type="text/css">
body{background:url($var)#fff !important;}
</style>

test;

return $res;
?>

main.php

<?php
$test = require_once('test.php');

echo $test;
?>
+5  A: 

“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.
…
?>
Konrad Rudolph
speedy, beat me. :)
Jayrox
+1  A: 

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.

adam
+5  A: 

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.

Pekka
I want to execute my php file and return html, js and etc but prepeared by php. Can i do it without $a = 'my html and etc'; return $a; ?
swamprunner7
@swamprunner you could use HEREDOC syntax, but it's not really what you want I think. Better go with `file_get_contents()` or Konrad's solution.
Pekka
Most PHP programmers don't even know this is possible, thank goodness :)
webbiedave
Oh yeah, thank you :)
swamprunner7
A: 

There's a bunch of very useful discussion on this very topic in the php online manual. Some of what was suggested here is mentioned there as well.

eykanal