Include, require & require_once

Misiur picture Misiur · Jun 4, 2010 · Viewed 9.7k times · Source

Today I've tried to include file that returns object. I always use require_once, however now I've noticed weird behavior of it.

File main.php

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

File index.php

$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 it like that? I thought that require and require_once are same thing, only require_once is more safe because it won't duplicate include.

Thanks.

Edit:

But when i use only require_once, I get bool(true) too. So require_once returns only result of include, not it's content?

Edit2:

LOL. I haven't noticed, that earlier I had required this file inside of my class which is created before this code execution ($this->file = require_once("langs/$name/main.php");)

So require_once worked as it should. Thanks guys!

Answer

tloach picture tloach · Jun 4, 2010

When you use include and require you get the result of the page you're referencing being included. When you use require_once it checks and sees that the page has already been loaded using require, so it returns true to tell you that it has been loaded successfully at some point.