cancer10
02-03-2010, 09:59 AM
HI People
How come the following code generates undefined variable error?
Error:
Notice: Undefined variable: abc in D:\xampp\htdocs\test2.php on line 6
<?php
error_reporting(E_ALL);
$abc = 'hello';
function xyz(){
echo $abc;
}
echo xyz();
?>
Any help will be appreciated
Thanks
Set the $abc into the function
<?php
function xyz() {
$abc = 'hello';
return $abc;
}
echo xyz();
?>
cancer10
02-03-2010, 10:16 AM
No, I want to access a variable that is declared outside a function, within that function. can we?
thekooliest
02-03-2010, 10:23 AM
You have to pass variables into a function, they cannot read variables created outside. So now, function xyz reads the first parameter entered (in this case $abc is sent in the line echo xyz($abc);) and uses it as variable $test within the function xyz...
<?php
$abc = 'hello';
function xyz($test){
echo $test;
}
echo xyz($abc);
?>
http://www.w3schools.com/php/php_functions.asp (scroll down to adding parameters)
Dormilich
02-03-2010, 11:06 AM
you could also make use of the superglobals (in this case the $GLOBALS array) that PHP provides.
dmgroom
02-03-2010, 12:36 PM
For a start you effectively are duplicating the echo command, once within the fuction and once when calling the function. Secondly you need to declare the variable global within the function.
<?php
error_reporting(E_ALL);
$abc = 'hello';
function xyz(){
global $abc;
echo $abc;
}
xyz();
?>
OR
<?php
error_reporting(E_ALL);
$abc = 'hello';
function xyz(){
echo $GLOBALS['abc'];
}
xyz();
?>
Fou-Lu
02-03-2010, 12:42 PM
globals destroy reusability. Pass you're variable as a parameter to you're function instead.