Include, require & require_once

Today I tried to include a file that returns an object. I always use require_once, but now I noticed its strange behavior.

Main.php file

$lang = false; $lang->name = "eng"; $lang->author = "Misiur"; $lang->text = "Text is test"; $lang->undefined = "Undefined"; return $lang; 

Index.php file

 $lang = include('langs/eng/main.php'); var_dump($lang); echo "<br />"; $lang = require('langs/eng/main.php'); var_dump($lang); echo "<br />"; $lang = require_once('langs/eng/main.php'); var_dump($lang); 

Result

 object(stdClass)#9 (4) { ["name"]=> string(3) "eng" ["author"]=> string(6) "Misiur" ["text"]=> string(12) "Text is test" ["undefined"]=> string(9) "Undefined" } object(stdClass)#10 (4) { ["name"]=> string(3) "eng" ["author"]=> string(6) "Misiur" ["text"]=> string(12) "Text is test" ["undefined"]=> string(9) "Undefined" } bool(true) 

Why is that? I thought that require and require_once are the same thing, only require_once is more secure because it will not duplicate include.

Thanks.

Edit:

But when I use only require_once, I also get bool (true). So require_once returns only the result of the include, not the content?

Edit2:

Lol. I did not notice that earlier I needed this file inside my class, which was created before this code execution ($ this-> file = require_once ("langs / $ name / main.php");)

So require_once worked as it should. Thanks guys!

+6
object include php require require-once
source share
4 answers

When you use include and require that you get the result of the page you are linking to is included. When you use require_once, it checks and sees that the page is already loaded using require, so it returns true to tell you that it was successfully loaded at some point.

+11
source share

That's for sure, and you are trying to duplicate include. When you require_once something that was not previously included or was not, you will get a return value.

EDIT: With this simple test in PHP 5.3.2, I get the return value when using require_once for the first time.

parent.php:

 <?php $first = require_once("child.php"); var_dump($first); $second = require_once("child.php"); var_dump($second); ?> 

child.php:

 <?php return "foo"; ?> 

He prints:

 string(3) "foo" bool(true) 
+7
source share

I assume you have open and close tags for both files? The PHP documentation on include mentions part of this. Example No. 5 on this page.

It seems that include , require and require_once all have the same functionality, only for this you need to emit an error instead of a warning, and require_once does not duplicate-include the file.

0
source share

Never use return with those included. Do not return the binding or assign any variable.

-one
source share

All Articles