PHP pass variable to include

前端 未结 13 2868
你的背包
你的背包 2020-11-27 17:19

I\'m trying to pass a variable into an include file. My host changed PHP version and now whatever solution I try doesn\'t work.

I think I\'ve tried every op

13条回答
  •  日久生厌
    2020-11-27 17:42

    You can use the extract() function
    Drupal use it, in its theme() function.

    Here it is a render function with a $variables argument.

    function includeWithVariables($filePath, $variables = array(), $print = true)
    {
        $output = NULL;
        if(file_exists($filePath)){
            // Extract the variables to a local namespace
            extract($variables);
    
            // Start output buffering
            ob_start();
    
            // Include the template file
            include $filePath;
    
            // End buffering and return its contents
            $output = ob_get_clean();
        }
        if ($print) {
            print $output;
        }
        return $output;
    
    }
    


    ./index.php :

    includeWithVariables('header.php', array('title' => 'Header Title'));
    

    ./header.php :

提交回复
热议问题