Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cannot get the return value of require_once function in PHP?

I already know that include_once would return true or false based on including that file. I've read a question on Stackoverflow about using require_once to return your value and print it out.

The problem is that I have an existing project in hand, and inside of that file they return an array. I want to get the output of require_once to see what result I've got, but I get 1 instead of array that contains data:

return array('data'=>$result_data,'error'=>null);

What I do is:

$ret = require_once $this->app->config('eshopBaseDir')."fax/archive.php";
print_r($ret);

Is there any workaround for this?

like image 245
Alireza Avatar asked Oct 08 '14 13:10

Alireza


People also ask

How does require_once work in PHP?

The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.

What is the difference between include_once () and require_once ()?

The only difference between the two is that require and its sister require_once throw a fatal error if the file is not found, whereas include and include_once only show a warning and continue to load the rest of the page.

When should I use require_once vs require in PHP?

The require() function is used to include a PHP file into another irrespective of whether the file is included before or not. The require_once() will first check whether a file is already included or not and if it is already included then it will not include it again.

Which of the following returns fatal error and stops execution of the PHP page during file inclusion A include B require C Include_once D Require_once?

require_once() Function php is a php script calling b. php with require_once() function, and does not find b. php, a. php stops execution causing a fatal error.


1 Answers

This indicated that the file has already been included at that point.

require_once will return boolean true if the file has already been included.

To check you can change to simply require:

$ret = require $this->app->config('eshopBaseDir')."fax/archive.php";
print_r($ret);

As a simple proof:

//test.php

return array('this'=>'works the first time');

//index.php

$ret = require_once 'test.php';
var_dump($ret);//array
$ret2 = require_once 'test.php';
var_dump($ret2);//bool true
like image 77
Steve Avatar answered Sep 17 '22 15:09

Steve