20

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?

Community
  • 1
  • 1
Alireza
  • 6,497
  • 13
  • 59
  • 132
  • 2
    You'll need to run your own tests, but returning from a require is such a marginal feature that it wouldn't surprise me if it doesn't support returning arrays. But fear not, just stick the array in a global variable and fetch it after requiring. PHP's lack of modularity is to your advantage in this case. – alexis Oct 08 '14 at 13:20
  • @alexis, it works by using GLOBAL. tnx – Alireza Oct 08 '14 at 13:26
  • @JohnConde That is incorrect – Steve Oct 08 '14 at 13:29
  • @alexis that's no more the case, [things have changed over time](https://www.php.net/manual/en/function.include.php) (search for "Handling Returns"). – Niki Romagnoli Aug 03 '21 at 13:57
  • Thanks, it's good to know that returning arrays is supported. (I was guessing back then anyway :-) ). – alexis Aug 04 '21 at 08:42

1 Answers1

32

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
Steve
  • 20,703
  • 5
  • 41
  • 67