Undefined variable?

HI People

How come the following code generates undefined variable error?

Error:

Notice: Undefined variable: abc in D:\\xampp\\htdocs\	est2.php on line 6
<?php 
error_reporting(E_ALL);
 $abc  = 'hello';

function xyz(){
	echo $abc;
}

echo xyz();

?>

Any help will be appreciated

Thanks

Because you are passing $abc into a function,
when you are inside the XYZ function, it doesn’t know of any variables except globals and whats inside it.

You could do…

<?php 
error_reporting(E_ALL);

$abc = 'hello';

function xyz(){
    global $abc;
    echo $abc;
}

xyz();


?>

but i’d do it this way… and set the output inside the function

<?php 
error_reporting(E_ALL);

function xyz($abc){
    echo $abc;
}

xyz('Hello');


?>

yes thanks but what you suggested is how not to show an error, what I want to know is why is it not able to access $abc as its already declared?

as JREAM said, the variable $abc is defined outside the function. The $abc inside the function exist ONLY inside that function - it has no knowledge of the other $abc variable.

In essence the function can only use the variables you give it in the arguments unless you declare them as global or are in a Class/OOP scenario.

More about scope here http://php.net/manual/en/language.variables.scope.php or google variable scope.