How to define a global function which would be accessible from any page?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Keeping track of variable instances
- Can php detect if javascript is on or not?
You could declare a function inside a function, be careful to call the outside function only once or you'll get an error.
If you want your function to always be available, without including it, do this:
Create your function in a php file.
In your php.ini 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
inphp.ini
to find the file.Put it in an include, then include it.
In include.php:
Then in every page you want to use it:
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
Seesaw
-
This technically may not be correct, depending on the context.
'Page' could be perceived as 'file', Eg "You must include the function's file within each file you want to use the function".
Once a function is defined in your program, it can be accessed from anywhere moving forward up until the program has finished executing.
Say you have this:
index.php:
boot.php
page.php
With that, your output would be
1119342949
.Of course, when you say 'page' you may literally mean a directly accessed stand-alone 'page file', in which case the answers from the other users will suffice. However, if you're looking to use the same function from different locations throughout your program, simply define it before you intend to use it and you can access it anywhere moving forward regardless of scope.
Edit:
To correct myself, this of course isn't true for things like class functions, but for normal functions this remains true.