📜 ⬆️ ⬇️

We read manuals - about one secret include

For those who come into the world of PHP with C or other languages, some features of the language, which are described in the documentation, are often revealing, but, nevertheless, they are often eluded.

Today I want to talk about the non-standard (from the point of view of most programmers) use of the include statement in PHP

It turns out that this operator, in addition to its main job, including an external file in your program, can also behave as a function, that is, return a value.

In order to obtain the “file value” it is sufficient in the included file, as in a function, to use the return operator. Then such constructions become possible:
')
a.php:
$ret = 'aaa';
return $ret;


b.php:
$b = include('a.php');
echo $b; // Displays 'aaa'


What can it be for?


On personal experience, I found two very practical and practical uses of this "quirk."

1. Building blocks.

In many CMS, leading their kinship from Nuke - this is both XOOPS and RunCMS and the new fork Ronny CMS uses a modular-block structure. The module implements a certain functionality, and displays its content in the blocks from which the page is formed.

This is done usually as follows. Each module has a list of blocks, and for the block, an include file and a function that outputs the content is set:
$block[0]['file'] = 'block_file.php';
$block[0]['func'] = 'show_func';


Accordingly, somewhere inside the CMS something like this happens
include($module . $block[0]['file']);
echo $block[0]['func']();


Thus, we have an extra level of abstraction and, more terribly, the possibility of a conflict of function names.

It is more rational to use the ability of the include operator to return a value from an include file:
echo include($block[0]['file']);
, which will simplify the code and get rid of the danger of matching function names.

This approach is applicable not only in CMS blocks, but also wherever it is necessary to divide the program into functional modules.

2. Use in configs

Just illustrate the code:

config.php:
$config['host'] = 'test.com';
$config['user'] = 'test';
$config['pwd'] = 'tESt';
return $config;


test.php:
$params = include('config.php');

All examples are conditional and are for illustrative purposes only.

PS Earlier this topic has already been raised, for example, here: habrahabr.ru/blogs/php/39034 , but I thought that there would be nothing wrong with repetition.

PPS The question about the value returned by include and about $$ a constructions I use at the interview with the programmers. They are not decisive, of course, but they let you understand how deeply a person knows the language used.

Source: https://habr.com/ru/post/78941/


All Articles