twitter
    Find out what I'm doing, Follow Me :)
If you have any question, suggestion or article topic for me to write, feel free to contact me through my shout box. ;) Some time I need an idea to write. hehe Hopefully I can help you and share my expertise.

php global variable

Last week I got an email from someone need my help to solve her problem. She asking me why there is no result when she do echo inside function.

this is an example code to illustrate her problem.


$lang = 'bahasa melayu';
function test(){
echo $lang;
}
test();
actually the problem is in variable declaration. The first $lang variable is a global scope variable while second $lang variable reference to local scope variable.


$lang = 'bahasa melayu'; //global scope variable
function test(){
echo $lang; //local scope variable
}

test(); //return ''
To solve this problem you need to declare local scope variable as global.


$lang = 'bahasa melayu'; //global scope variable
function test(){
GLOBAL $lang; //declare $lang as a global variable
echo $lang; //reference to global scope variable
}

test(); //return 'bahasa melayu'
others solution, you may sent variable into function parameter as an example below


$lang = 'bahasa melayu'; //global scope variable
function test($param){
echo $param;
}

test(); //return 'bahasa melayu'
Happy coding ;)

0 comments:

Post a Comment