Thursday, May 3, 2012

Declaring global variables in a php script

If you have a php script to write with different functions defined in it and you would want to use a global variable in those functions, you might be tempted to do the following:

<?php
    global $x;
    function m1() {
         $a = $x;
    }
    function m2() {
        $b = $x;
    }
?>

Well, it seems the obvious way of using the global variable. But it's NOT! It is not just correct and the php script will be failed to run.


The correct way of accessing would be to declare the variable as global inside the functions! Like below:

<?php
    $x;
    function m1() {
         global $x;
         $a = $x;
    }
    function m2() {
        global $x;
        $b = $x;
    }

?>

Hope this helps you!

Help me Learn, Help you Learn

KVK

No comments:

Post a Comment