Search code examples
phpincluderequire

Make $var set in a PHP file work in other PHP file included/required by the initial one


I have a following code in the initial PHP file:

$var = $another_var;
echo 'Some text '.$var.' some more text.';

The code which produces $another_var can not be moved to any other file.

Now I want every text string of the whole initial PHP file including the one in the example to put to an extra PHP file and include or require it by the initial one. Like this:

// required.php file
$text_string_1 = 'Some text '.$var.' some more text.';

and

// Initial PHP file
<?php require('required.php'); ?>
$var = $another_var;
<div><?php echo $text_string_1; ?>

Expectedly it doesn't work. I assume that's because the required.php file knows nothing about the $var's value as it was set in another file which is just going to adopt required.php.

Is there any workaround for this? Preferably keeping both files as simple as possible.


Solution

  • You could change to a template approach. And substitute later:

    <?php
    
    $template = 'Hello %s, this could be a solution.';
    
    $txt = sprintf($template, 'Foo');
    
    echo $txt;
    

    Output:

    Hello Foo, this could be a solution.