I have code something like this:
<?
$a="localhost";
function body(){
global $a;
echo $a;
}
function head(){
global $a;
echo $a;
}
function footer(){
global $a;
echo $a;
}
?>
is there any way to define the global variable in one place and make the variable $a
accessible in all the functions at once? without making use of global $a;
more?
My Answer:
To declare a global variable in PHP, you can use the `global` keyword followed by the variable name inside a function. Here is an example:
php
$globalVar = "I am a global variable";
function myFunction() {
global $globalVar;
echo $globalVar;
}
myFunction(); // Output: I am a global variable
In this example, `$globalVar` is declared outside of the function and then accessed inside the function using the `global` keyword. This allows the variable to be accessed and modified within the function as if it were a local variable.
Rate this post
3 of 5 based on 2329 votesComments