PDA

View Full Version : Sharing code between pages in PHP.



Incompetnce
02-04-2007, 08:59 AM
This question is probably pretty trivial, but I've been having trouble with it.

Basically, I have an array and a couple of variables that I use on several different pages on my site. I was thinking of having the variables just in a text file and having the php retrieve it from there. Then I would only have to alter the text file, rather than having to change each page's code individually.

My friend suggested something involving reading each line of text and entering it ino an array individually. But this sounds a lot more complicated than I need. I just want each page to read the text file and then "pretend" its contents were in the php code.

Any ideas?

Chris
02-04-2007, 09:13 AM
Ya... simple...

Make a PHP include file with the variable assignments in it.

then in whatever php file you need to access the variables, include it.



<? include("file-with-vars.php"); ?>

If you need to be editing & changing the variables automatically though you'd want to just store them in a database.

Incompetnce
02-04-2007, 09:18 AM
OK thanks. and the "file-with-vars.php" would just look like:
<?
$var1=x;
$var2=y
etc...
?>
right?

mobilebadboy
02-04-2007, 09:41 AM
Right.

Then just include that at the top of the page(s), then throughout each page with the include you can call $var1, etc as many times as you like.