Bas
Bas

Reputation: 2210

Returning the file contents

When I have a php file that looks like this (no scripts, just returning values):

return [1, 2, 3, 4, 5];

I have to use require or include to get those file contents like this:

$contents = require "data.php";

Is this this the common way to get data out of a file or can it be done in more ways?

Upvotes: 0

Views: 81

Answers (2)

Bas
Bas

Reputation: 2210

As @MarkBaker posted in the comments:

It's only common if the "data" is executable code, in which case it's very common.

A file that contained <?php return [1, 2, 3, 4, 5]; would be executable code; a file that contained 1, 2, 3, 4, 5 would be non-executable code. There's no code statements for PHP to execute.

Using include or require on a file that contained the latter wouldn't achieve anything; you'd need to use file_get_contents() (or similar) to read the actual data into a variable.

Upvotes: 0

gintko
gintko

Reputation: 697

For real, this way I see first time, and can I ask you, this works? Anyway, it's not a good practice. It's better to describe function in file, and then use function.

data.php:

function get_array(){
    return [1, 2, 3, 4 ,5];
}

and then use it like:

include('data.php');
$contents = get_array();

If you want, to get all file content as string, you can use file_get_contents:

$contents = file_get_contents('data.php');

And what's difference between include and require? When you use include, and file doesn't exists, you dont't get fatal error.

Upvotes: 1

Related Questions