2

Passing Variables to a Required Script in PHP

Posted (Updated ) in PHP

Have you ever wanted to require a script in PHP without it inheriting all your current scripts’ variables? Did you instead want to pass different variables to it? With this nifty little function you’ll be able to do just that:

function require_with($pg, $vars)
{
	extract($vars);
	require $pg;
}

By placing PHP’s require function in a function of our own, we hide all our current script’s variables from the page we’re requiring. This is called variable scope. If that weren’t useful enough, we can also use the extract function to pass variables of our own into our function – allowing our required page to see them.

Here’s a usage example

<?php
	//my_page.php
	function require_with($pg, $vars)
	{
		extract($vars);
		require $pg;
	}
 
	//This will be hidden from required.php
	$var1 = 'howdy';
 
	//Create 'var2' and 'var3' variables and pass them to required.php
	require_with('required.php', array(
		'var2' => 'hi',
		'var3' => 'yo'
	));
<?php
	//required.php
	if ( isset($var1) ) echo $var1.'<br/>';
	if ( isset($var2) ) echo $var2.'<br/>';
	if ( isset($var3) ) echo $var3.'<br/>';

Load my_page.php in a browser. With any luck you should get the following output:

hi
yo