Home » Php » php – Include, require & require_once

php – Include, require & require_once

Posted by: admin July 12, 2020 Leave a comment

Questions:

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!

How to&Answers:

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.

Answer:

That’s exactly it, and you’re trying to duplicate include. When you require_once something that hasn’t been included or required before, you will get the return value.

EDIT: With this simple test on 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";
?>

It prints:

string(3) "foo"
bool(true)

Answer:

I’m assuming that you do have open and closing tags on both files? The PHP documentation on include mentions some of this. Check out example #5 on that page.

It looks like include, require, and require_once all have the same functionality, just that require emits an error instead of warning, and require_once doesn’t duplicate-include a file.

Answer:

Never use return with includes.
Do not return anting and do not assign any variable.