Undefined variable error when calling a function f

2019-09-05 08:50发布

问题:

The following PHP page

<?php
$a = "World";

function say() {
    echo $a;
}
?>

Hello, <?php say(); ?>

fails with:

Undefined variable: a in test.php on line 5

Could someone explain me why, and what is the best way to fix this?

回答1:

you have to define variable as global inside the function

<?php
 $a = "World";

function say() {
global $a;
echo $a;
}
 say(); 
?>


标签: php scope