How to use require connect not the whole file, but only a part of it? For example:
index.php:

 $text = 'Привет'; echo $text; $day = 21; echo $day; 

second.php:

 require 'index.php'; 

How to connect, let's say, only $text = 'Привет'; and echo $text; ?

  • no, it's impossible. place the necessary code in the function / method. - etki
  • Well, you can turn around: read the lines of the file and drive them into eval() - lampa

2 answers 2

This is a very strange approach and it is not necessary to do so.

But if you really want to do this, then:

  1. Before require declare a variable, for example, $codePart = "part_1" ;
  2. File index.php format as follows:

 if (!empty($codePart)) { switch ($codePart) { case 'part_1': $text = 'Привет'; echo $text; break; case 'part_2': $day = 21; echo $day; break; } } 

In second.php you will have something like:

 $codePart = 'part_1'; require 'index.php'; 

In fact, the file will be included all, but only the selected part will be displayed. This approach is bad and dead end.

It is much better (although not also optimally) to put the blocks you need into separate functions, and then just call them where necessary.


 index.php: <?php function partOne() { echo 'Привет'; } function partTwo() { echo 21; } second.php: <?php include('index.php'); partOne(); //выводится "Привет" partTwo(); //выводится 21 

So you will have the file included exactly once, and the blocks can be output where necessary.

Better yet, read about template engines.

    In php, include / require connects and executes the file. You will not be able to import part of the file, as for example it is done in Python or Java. In essence, include / require inserts the contents of the file instead of its call, even if it is in the function body, except for the so-called "magic" constants of type FILE or DIR that are processed by the php interpreter before connecting.