简体   繁体   中英

Undefined variable error when calling a function from another snippet

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?

you have to define variable as global inside the function

<?php
 $a = "World";

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM