Undefined variable error when calling a function from another snippet

倖福魔咒の 提交于 2019-12-12 01:34:54

问题


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(); 
?>


来源:https://stackoverflow.com/questions/14301958/undefined-variable-error-when-calling-a-function-from-another-snippet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!