返回所需文件中的对象并引用它

Returning an object in a required file and referencing it

假设我们有一个文件 (foo.php):

<?php
// foo.php
$a = new Foo();
return $a; //this is the part that I'm questioning

我见过两种使用 $a 的方法:

//in this case, bar.php doesn't have the "return" statement
require('foo.php');
$a->run();

$a = require('foo.php');
$a->run();

我的问题是,为什么真的需要 return 语句和第二种方法?实际效果或性能上有差异吗?

-- 编辑 -- 作为参考框架,这个 "strategy"(带有 return)至少可以在 CodeIgniter 和 Laravel.

的某些版本中找到

没有实际区别。

在这两种情况下,$a 变量最终将在主脚本中定义。

两种设计都不太理想。要包含的文件不应有任何逻辑,只有声明。

如果有的话,这只会稍微好一点:

<?php
//foo.php
return new Foo();
//bar.php
$foo = require 'foo.php';

这样至少你可以在消费脚本中定义任何你想要的变量,而不需要知道foo.php定义的变量的名称。