Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define global functions in PHP

How can I define a global function which would be accessible from any page?

like image 465
Sussagittikasusa Avatar asked Dec 16 '10 08:12

Sussagittikasusa


People also ask

How can define global variable in PHP?

Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.

How do you make a global function?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

How do you define a function in PHP?

PHP User Defined FunctionsA function is a block of statements that can be used repeatedly in a program. A function will not execute automatically when a page loads. A function will be executed by a call to the function.

What are global functions?

Global functions allow you to perform processing at a specific resolution and extent. By default, global functions process rasters at the source resolution and full extent. This means that applying a global function may take some time, depending on the size of the outputs.


2 Answers

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.

like image 65
user2656037 Avatar answered Sep 21 '22 00:09

user2656037


In file include.php:

function myGlobalFunction() {     // Do something } 

Then in every page you want to use it:

include 'include.php'; myGlobalFunction(); 
like image 34
Jordi Avatar answered Sep 21 '22 00:09

Jordi