Search code examples
phpvariablesincluderequire-once

Get variables from included file


How do I use variables from an included file, and use it for other included files as well?

index

<?php
$tmp = new template($connect);
$tmp->globals('index');
$logged_in = false; //works in all included files
?>
<html>
  <head>
    <?php $tmp->template('head'); ?> //class method to include file
  </head>
  <body>
    <?php echo $description; ?> //does not work either

include_head.php

 <title><?php echo $title; ?></title>//does not echo anything

index_globals.php

<?php
    $title="title";
    $description="description";   
 ?>

How I am including

public function template($file){
    if(isset($file) && file_exists($this->dir.$file.".php")){
        ob_start();
        include($this->dir.$file.".php");
        $template = ob_get_contents();
        return $template;
     }
}

Globals Function

public function globals($name){
  if(isset($name) && file_exists($this->dir.$name."_globals.php")){
      include($this->dir.$name."_globals.php");
  }
}

Solution

  • You can "import" the globals by returning an array instead of declaring the variables:

    <?php
    // index_globals.php
    
    return [
        'title' => 'title',
        'description' => 'description',
    ];
    

    Then, from the globals() function you import it into a local property:

    private $context = [];
    
    public function globals($name)
    {
        if (isset($name) && file_exists($this->dir.$name."_globals.php")) {
            $this->context = include($this->dir.$name."_globals.php");
        }
    }
    

    Finally, update the template() method:

    public function template($file)
    {
        if (isset($file) && file_exists($this->dir.$file.".php")) {
            extract($this->context);
            ob_start();
            include($this->dir.$file.".php");
            $template = ob_get_contents();
            return $template;
         }
    }
    

    Note that your index will not have access to $description in this case either, but it shouldn't be hard to gain access via the template instance.