How to define global functions in PHP

You could declare a function inside a function. Be careful to call the outside function only once or you'll get an error.

class MyClass {

  function declareGlobalsFn () {
    // Functions declared inside a function have global scope

    function globalfn1() {echo "fn1";}

    function globalfn2() {echo "fn2";}
  }
}

$ob = new MyClass();
$ob->declareGlobalsFn();

globalfn1(); // fn1
globalfn2(); // fn2

To expand on luarwo's answer, you can declare the function right in your class constructor. This could make your class a sort of function library, where the functions are accessible from any page where you create your class instance.

Sandbox\MyGameLib

<?php
namespace Sandbox;
class MyGameLib {
    public function __construct() {
        if (!function_exists('loveGame')) {
            function loveGame($game) {
                print "The game $game is awesome";
            }
        }
    }
}

Seesaw

<?php
namespace Seesaw;
use Sandbox\MyGameLib;

$m = new MyGameLib();
loveGame('Tempest');

The game Tempest is awesome


If you want your function to always be available, without including it, do this:

  1. Create your function in a PHP file.

  2. In your php.ini file, search for the option auto_prepend_file and add your PHP file to that line, like this:

    `auto_prepend_file = "/path/to/my_superglobal_function.php"`
    

    Or if you write it with a non absolute path, like this:

    auto_prepend_file = "my_superglobal_function.php"

    It will look in your include_path in php.ini to find the file.


In file include.php:

function myGlobalFunction() {
    // Do something
}

Then in every page you want to use it:

include 'include.php';
myGlobalFunction();