PHP - 读取另一个PHP文件的内容而不回显

I am trying to reach the contents of a PHP file without the file actually outputting what it would usually do. Here is my test code:

File1 (test1.php)

<?php
    ob_start();
    include_once './test2.php';
    $test = ob_get_contents();

    echo $test;
?>

and here is file2 (test2.php)

<?php
     $testVar = 'Name!';
?>
<div class="testClass"><?php echo $testVar?></div>
<p>Spam2</p>

and I want it to only do this because of the

echo $test

line NOT because the file is outputting the content.

<p>Spam2</p><div class="testClass">Name!</div>
<p>Spam2</p></body>

due to the echo, but it returns this

<p>Spam2</p><div class="testClass">Name!</div>
<p>Spam2</p></body>
<p>Spam2</p><div class="testClass">Name!</div>
<p>Spam2</p></body>

So how do I get it to only return the content once?

Don't echo $test;. PHP is executing as it should. Since ./test2.php shows Spam in HTML it appears on the page, then you assign the page contents to a variable and echo it. What do you expect?

If you have 2 files say: app/index.php and app/config.php you can just use the return keyword to return some content from the config.php file. And then, when you include the file whatever you returned from config.php can be saved to a variable.

Example:

First return whatever you want from the config.php file (could be an array, string, etc).
<?php 
return ['name' => 'Spam'];
Then in the index.php:
<?php
$contents = include_once('config.php');
echo $contents;