Search code examples
phpscopereturnrequire

Returning an object in a required file and referencing it


Suppose we have a file (foo.php):

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

I have seen two approaches to using $a:

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

and

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

My question is, why is the return statement and second approach really needed? Is there some difference in the actual effect or in performance?

-- edit -- As a frame of reference, this "strategy" (with the return) is found in at least some versions of both CodeIgniter and Laravel.


Solution

  • There is no practical difference.

    In both cases the $a variable will end up defined in the main script.

    Both designs are less than ideal. Files to be included should not have any logic in them, only declarations.

    If anything this would be only slightly better:

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

    This way at least you can define any variable you want in the consuming script, and do not need to know what's the name of the variable that foo.php defines.