How can I declare a global variable in php?

0 votes

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?

Oct 1 in PHP by kartik
• 35,620 points
47 views

1 answer to this question.

0 votes

Hello @kartik,

The $GLOBALS array can be used instead:

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

function body(){

    echo $GLOBALS['a'];
}

Hope it helps!!
Thank you!!

answered Oct 1 by Niroj
• 77,360 points

Related Questions In PHP

0 votes
1 answer

How can I include a php file and also send query parameters in php?

Hello, You could do something like this to ...READ MORE

answered Nov 10 in PHP by Niroj
• 77,360 points
47 views
0 votes
1 answer

How to access a global variable in a PHP function?

Hello @kartik, It is not working because you have to ...READ MORE

answered Nov 10 in PHP by Niroj
• 77,360 points
20 views
0 votes
1 answer

How can we create a session in PHP?

Hello @kartik, session_start() function is used in PHP to ...READ MORE

answered Mar 27 in PHP by Niroj
• 77,360 points
100 views
0 votes
1 answer

How can I handle the warning of file_get_contents() function in PHP?

Hello @kartik, This is fairly simple: if (!$data = ...READ MORE

answered Apr 7 in PHP by Niroj
• 77,360 points
1,524 views
0 votes
1 answer

jQuery AJAX fires error callback on window unload - how do I filter out unload and only catch real errors?

Hello, In the error callback or $.ajax you have three ...READ MORE

answered Apr 27 in Java-Script by Niroj
• 77,360 points
445 views
0 votes
1 answer

How do I pass command line arguments to a Node.js program?

Hello @kartik, If your script is called myScript.js ...READ MORE

answered May 5 in Java-Script by Niroj
• 77,360 points
690 views
0 votes
1 answer

Error:Issue when trying to use IN() in wordpress database

Hello @kartik, Try this code : // Create an ...READ MORE

answered May 8 in PHP by Niroj
• 77,360 points
91 views
+2 votes
1 answer

How do I debug Node.js applications?

Hello @kartik, Use node-inspector  from any browser supporting WebSocket. Breakpoints, ...READ MORE

answered Jul 8 in Node-js by Niroj
• 77,360 points
87 views
0 votes
1 answer

How can I connect to a Tor hidden service using CURL in PHP?

Hello @kartik, I use Privoxy and cURL to scrape Tor ...READ MORE

answered May 19 in PHP by Niroj
• 77,360 points
873 views
0 votes
1 answer

How can I get the classname from a static call in an extended PHP class?

Hello @kartik, __CLASS__ always returns the name of the ...READ MORE

answered Oct 27 in PHP by Niroj
• 77,360 points
30 views