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

Alireza picture Alireza · Oct 8, 2014 · Viewed 16.1k times · Source

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?

Answer

Steve picture Steve · Oct 8, 2014

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