PHP Global in Functions

How to define global functions in PHP

In file include.php:

function myGlobalFunction() {
// Do something

Then in every page you want to use it:

include 'include.php';

PHP define global variables for functions?

I suggest that you store your array globally using the $GLOBALS, and instead of using echo to print an array, use the print_r method instead.

$GLOBALS["titleArray"] = array('world');

function foo(){

function boo(){
array_push($GLOBALS["titleArray"], "Hello");



Access a global variable in a PHP function

It's a matter of scope. In short, global variables should be avoided so:

You either need to pass it as a parameter:

$data = 'My data';

function menugen($data)
echo $data;

Or have it in a class and access it

class MyClass
private $data = "";

function menugen()
echo this->data;


See @MatteoTassinari answer as well, as you can mark it as global to access it, but global variables are generally not required, so it would be wise to re-think your coding.

PHP global in functions

Globals are evil

This is true for the global keyword as well as everything else that reaches from a local scope to the global scope (statics, singletons, registries, constants). You do not want to use them. A function call should not have to rely on anything outside, e.g.

function fn()
global $foo; // never ever use that
$a = SOME_CONSTANT // do not use that
$b = Foo::SOME_CONSTANT; // do not use that unless self::
$c = $GLOBALS['foo']; // incl. any other superglobal ($_GET, …)
$d = Foo::bar(); // any static call, incl. Singletons and Registries

All of these will make your code depend on the outside. Which means, you have to know the full global state your application is in before you can reliably call any of these. The function cannot exist without that environment.

Using the superglobals might not be an obvious flaw, but if you call your code from a Command Line, you don't have $_GET or $_POST. If your code relies on input from these, you are limiting yourself to a web environment. Just abstract the request into an object and use that instead.

In case of coupling hardcoded classnames (static, constants), your function also cannot exist without that class being available. That's less of an issue when it's classes from the same namespace, but when you start mix from different namespaces, you are creating a tangled mess.

Reuse is severly hampered by all of the above. So is unit-testing.

Also, your function signatures are lying when you couple to the global scope

function fn()

is a liar, because it claims I can call that function without passing anything to it. It is only when I look at the function body that I learn I have to set the environment into a certain state.

If your function requires arguments to run, make them explicit and pass them in:

function fn($arg1, $arg2)
// do sth with $arguments

clearly conveys from the signature what it requires to be called. It is not dependent on the environment to be in a specific state. You dont have to do

$arg1 = 'foo';
$arg2 = 'bar';

It's a matter of pulling in (global keyword) vs pushing in (arguments). When you push in/inject dependencies, the function does not rely on the outside anymore. When you do fn(1) you dont have to have a variable holding 1 somewhere outside. But when you pull in global $one inside the function, you couple to the global scope and expect it to have a variable of that defined somewhere. The function is no longer independent then.

Even worse, when you are changing globals inside your function, your code will quickly be completely incomprehensible, because your functions are having sideeffects all over the place.

In lack of a better example, consider

function fn()
global $foo;
echo $foo; // side effect: echo'ing
$foo = 'bar'; // side effect: changing

And then you do

$foo = 'foo';
fn(); // prints foo
fn(); // prints bar <-- WTF!!

There is no way to see that $foo got changed from these three lines. Why would calling the same function with the same arguments all of a sudden change it's output or change a value in the global state? A function should do X for a defined input Y. Always.

This gets even more severe when using OOP, because OOP is about encapsulation and by reaching out to the global scope, you are breaking encapsulation. All these Singletons and Registries you see in frameworks are code smells that should be removed in favor of Dependency Injection. Decouple your code.

More Resources:

  • How is testing the registry pattern or singleton hard in PHP?
  • Flaw: Brittle Global State & Singletons
  • static considered harmful
  • Why Singletons have no use in PHP
  • SOLID (object-oriented design)

How to declare a global variable in php?

The $GLOBALS array can be used instead:

$GLOBALS['a'] = 'localhost';

function body(){

echo $GLOBALS['a'];

From the Manual:

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:

class MyTest
protected $a;

public function __construct($a)
$this->a = $a;

public function head()
echo $this->a;

public function footer()
echo $this->a;

$a = 'localhost';
$obj = new MyTest($a);

Declaring a global variable inside a function

you have to define the global var in the second function as well..

// global scope
$ref_id = 1;

global $ref_id;
$ref_id = $rid;

global $ref_id;


Having a PHP function use a global variable as a default?

You could use a constant. Define it at the top of a file and let your functions use that. E.g.

define('CUSTOM_TIMEZONE', 'Mountain');

function tell_time($values, $timezone = CUSTOM_TIMEZONE) {
// Your code here

Just change the constants value and it's changed everywhere.

Related Topics

Leave a reply