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
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).
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).
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
You can read more about variable scopes in the manual
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.