PHP Global Variables

Rad

...
Reaction score
228
Right now I'm designing my own template with PHP. Trying to make it as easy to edit as possible in the future and right now its going well. I broke up the different parts into seperate PHP files and include them on the page.

I want one global file, called "strings.php" that will hold the primary data of the theme, so I only need to edit it once and can edit them all in the same place.

I have one called "style.php" which is basically a stylesheet with variables, that works great but doesn't require what I'm looking for...

I'm trying to include the "strings.php" variables on all of the pages that I am using and will use in the future. So I put the include near the top of my page which looks like this so far:

PHP:
/* INDEX.php */
<?php 
  include "inc/strings.php"; // This file is where you will edit the title, subtitle, page names etc. of the site 
?>
<title><?php echo $global_sitename ?></title> // Works fine

/* STRINGS.php */
<?php
	$global_sitename = "rads site";
	$global_title = "Rad's Site";
	$global_subtitle = "Welcome to my website";
?>

/* HEADER.php */
<div id="topleft" class="left">
	<?php $title; ?> //Value is ''
	<BR />
	<?php $subtitle; ?> //Value is ''
</div>

I'm thinking PHP parses the includes before it includes them. Even if I redeclare the variables in the index.php the other included files don't work.

Is the only other option to include "strings.php" in each include file?
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
Use require() instead of include() if you really need the other file.

The difference between both is that require() throws a fatal error if it can't find the file. Beside of that, there's nothing wrong with your approach.

When used inside a function, you have to declare the variable:

PHP:
<?php

$myVar = 'test';

function myFunc()
{
  global $myVar;
  print $myVar;
}

?>

As for your code: better include print :p

PHP:
<?php print $global_subtitle; ?>
 

Rad

...
Reaction score
228
So you actually do need the Global on there, I'm used to autoit where you declare the variable as a global first, rather than "grabbing" the variable from the previous scope later.

That fixed that, but is there some reason why print is better than echo? I've used both but never noticed. I'll just go look those up :rolleyes:

Thanks
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top