Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: variable not working inside of function?

Tags:

function

php

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?

like image 592
matt Avatar asked Jun 14 '10 21:06

matt


People also ask

How can access global variable inside function in PHP?

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.

Why is my variable undefined PHP?

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.

How do you define a variable accessible in function in PHP script?

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.

What does $globals mean in PHP?

$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.


1 Answers

Because it's not defined in the function.

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.

like image 137
Joshua Pinter Avatar answered Sep 24 '22 06:09

Joshua Pinter