PHP access global variable in function

2019-01-17 09:33发布

问题:

According to the most programming languages scope rules, I can access variables that defined outside of functions inside them, but why this code doesn't work?

<?php
$data = 'My data';

function menugen(){   
    echo "[".$data."]";
}

menugen();
?>

There is [] in output.

回答1:

It is not working because you have to declare which global variables you'll be accessing:

$data = 'My data';

function menugen() {
    global $data; // <-- add this line

    echo "[".$data."]";
}

menugen();

otherwise you can access it as $GLOBALS['data'], see http://php.net/manual/en/language.variables.scope.php

Even if a little OT, I'd suggest you avoid using globals at all and prefer passing as parameters.



回答2:

You can do one of the following:

<?php
$data='My data';
function menugen(){
    global $data;
    echo "[".$data."]";
}
menugen();

Or

<?php
$data='My data';
function menugen(){
    echo "[".$GLOBALS['data']."]";
}
menugen();

That being said, overuse of globals can lead to some poor code. It is usually better to pass in what you need. For example instead of referencing a global database object you should pass in a handle to the database and act upon that. This is called Dependency Injection. It makes your life a lot easier when you implement automated testing (which you should).



回答3:

It's a matter of scope. In short, Global variables should be avoided SO:

You either need to pass it as a parameter:

$data = 'My data';

function menugen($data)
{
    echo $data;
}

OR have it in a class and access it

class MyClass
{
    private $data = "";

    function menugen()
    {
        echo this->data;
    }

}

Edit: See @MatteoTassinari answer as well as you can mark it as global to access it but global vars are generally not required so it would be wise to re-think your coding.



回答4:

Another way to do it:

<?php

$data = 'My data';

$menugen = function() use ($data) {

    echo "[".$data."]";
};

$menugen();


回答5:

You need to pass the variable into the function:

$data = 'My data';

function menugen($data)
{
    echo $data;
}


回答6:

If you want you can use "define" function but this function create a constants which can't be changed once defined.

<?php
define("GREETING", "Welcome to W3Schools.com!");

function myTest() {
    echo GREETING;
}

myTest();
?>

http://www.w3schools.com/php/php_constants.asp



标签: php scope