How to pass arguments to an included file?

Include has the scope of the line it’s called from.

If you don’t want to create new global variables, you can wrap include() with a function:

function includeHeader($title) {
    include("inc/header.php");
}

$title will be defined in the included code whenever you call includeHeader with a value, for example includeHeader('My Fancy Title').

If you want to pass more than one variable you can always pass an array instead of a string.

Let’s create a generic function:

function includeFile($file, $variables) {
    include($file);
}

Voila!

Using extract makes it even neater:

function includeFileWithVariables($fileName, $variables) {
   extract($variables);
   include($fileName);
}

Now you can do:

includeFileWithVariables("header.php", array(
    'keywords'=> "Potato, Tomato, Toothpaste",
    'title'=> "Hello World"
));

Knowing that it will cause variables $keywords and $title to be defined in the scope of the included code.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)