echo $path; //working
function createList($retval) {
echo $path; //not working
print "<form method='POST' action='' enctype='multipart/form-data'>";
foreach ($retval as $value) {
print "<input type='checkbox' name='deletefiles[]' id='$value' value='$value'>$value<br>";
}
print "<input class='submit' name='deleteBtn' type='submit' value='Datei(en) löschen'>";
print "</form>";
}
what am I doing wrong? why is $path printed correctly outside of the createList
function, but it's not accessible inside the function?
Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.
This error means that within your code, there is a variable or constant which is not set. But you may be trying to use that variable. The error can be avoided by using the isset() function.
To access the global variable within a function, use the GLOBAL keyword before the variable. However, these variables can be directly accessed or used outside the function without any keyword.
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
There are a few ways to go about this:
1) Use what Alex said by telling the function it is a global variable:
echo $path; // working
function createList($retval) {
global $path;
echo $path; // working
}
2) Define it as a constant:
define(PATH, "/my/test/path"); // You can put this in an include file as well.
echo PATH; // working
function createList($retval) {
echo PATH; // working
}
3) Pass it into the function if it's specific to that function:
echo $path; // working
function createList($retval, $path) {
echo $path; // working
}
Based on how the function really works, one of those will do ya.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With