user2503040
user2503040

Reputation:

How to make a PHP variable available in all pages

I recently took a dive into wordpress, and I noticed something really unusual, When coding I noticed that a particular variable called the $post variable was available for me to manipulate whenever I need it, as along as my page is within the wp-includes, wp-themes or wp-plugins folder without me calling any external page or function.

So I started developing a site without wordpress hoping to understand the mystery behind that anomaly..

I would appreciate all help on making me understand this phenomenon. I would like to use such technique in building sites. Thanks...

Upvotes: 2

Views: 5986

Answers (3)

Hanky Panky
Hanky Panky

Reputation: 46900

That's not an anomaly. That variable is present in global scope and is being defined in either of the files that you have mentioned. You can easily do it like

include.php

<?php
$myGlobal="Testing";
?>

anyfile.php

<?php
include "include.php";
echo $myGlobal;
?>

And you can use it in your functions as well, as long as you refer to the global one, for example

anotherfile.php

<?php
include "include.php";
function test()
{
 global $myGlobal;
 echo $myGlobal;
}
test();
?>

Theory

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well

By declaring (a variable) global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

Go through this PHP Doc once and you will have much better idea of how it all works.

Upvotes: 3

Mr. Smit
Mr. Smit

Reputation: 2532

php.ini register_globals = on

$post $get will be available anywhere

Upvotes: 0

Yarik Dot
Yarik Dot

Reputation: 1113

Take a look at global variables:

http://php.net/manual/en/language.variables.scope.php

and superglobal as well:

http://www.php.net/manual/en/language.variables.superglobals.php

Upvotes: 0

Related Questions