php undefined variable, doesnt get unset

天涯浪子 提交于 2019-12-24 19:15:54

问题


The variable $WebSiteDirectory never gets unset how ever i still get an error message

the variable gets set in "/../Include/ini.inc.php":

$WebSiteDirectory = "mydir\";
$newLine = "<br />";
$phpNewLine = "\n";

the place its getting stuffed up is :

echo $WebSiteDirectory; // this line is fine 
function theFunction($VAR) {
$dir = $WebSiteDirectory."my other dir"; // this line gets an error
var_dump($dir);
return file_exists($dir);
}

not sure there the error if forming. However, i also reuse $WebSiteDirectory later on the the program so i know it's not getting unset anywhere. i'm pretty sure im blind


回答1:


In PHP variables outside of a functions scope are not visible.

You must pass in your $WebSiteDirectory into the function as a parameter, or you can use the global keyword

function theFunction($VAR){
    global $WebSiteDirectory

Please read up a little on variable scope in the PHP manual first as it illustrates some good reasons for and against this method:

http://www.php.net/manual/en/language.variables.scope.php




回答2:


Add Your variables into your function

function theFunction($VAR) {

$WebSiteDirectory = "mydir";
$newLine = "<br />";
$phpNewLine = "\n";

$dir = $WebSiteDirectory."\my other dir"; // this line gets an error
var_dump($dir);
return file_exists($dir);
}

Or you can initialize this variable into global variable

global $WebSiteDirectory = "mydir";
global $newLine = "<br />";
global $phpNewLine = "\n";

Then only you can access this variable into your functuion



来源:https://stackoverflow.com/questions/20942909/php-undefined-variable-doesnt-get-unset

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