Search code examples
phpcodeigniterglobal-variablesglobal

Declaring and using global variables does not behave same in core php as in codeigniter


In Core php for global scope Example-1 works ok, and prints B=15 because of addition of b=a+b

but in codeigniter it prints B=10 which is $b's initial value, this means global scope does not work same as core php in codeigniter.

Example-1 works ok in core php but does not work in codeigniter

$a = 5;
$b = 10;

function myTest() {
    global $a, $b;
    $b = $a + $b;
}

myTest();
echo "B=$b"; //prints "B=15" in core php and "B=10" in Codeigniter

Example-2 works ok in core php and in codeigniter Both

global $a,$b;
$a = 5;
$b = 10;

function myTest() {
    global $a, $b;
    $b = $a + $b;
}

myTest();
echo "B=$b";//prints "B=15" in core php and in Codeigniter both.

i have used this Example-2 in my codeigniter view.

I know that the Example-2 is not correct syntactically but Example-1 is correct syntactically but then my question is :

why it is not working in codeigniter and why Example-2 which has two time initialization of global works in codeigniter


Solution

  • The view (where you write your code) is being included and executed inside a class method (which means that the code in your views aren't in the global scope).

    For example #1:

    If you use global $a; in your function (which technically will be defined inside the method), it will use $a from the global scope, while you've defined $a in the views scope (which is the scope of the view-class method).

    For example #2:

    When you use global $a; before you define the variable, you will be using the $a-variable from the global scope on both occasions, which is why that works

    References:

    You can read more about variable scopes in the manual

    Notes:

    1. This isn't anything specific to CodeIgniter. This is simply how scopes work in PHP.
    2. Using global is considered an anti-pattern and should be avoided when ever possible (which you can, in most situations) since it can make debugging a real pain and you can easily introduce unwanted side effects.
    3. I would recommend that you don't put functions inside the views. Add them as helper functions that you can load before you load your views. That will make it easier to find your functions (since they are all in the same place) and can easily be reused.