tags:

views:

77

answers:

5

Okay, weird problem. I have the following php code:

<?php

$identifier = $_POST['DEPT'];

function displaydata(){
  return $identifier;
}

?>

HTML CODE HERE

<?php echo displaydata(); ?>

This results in a blank page. However, when I replace

function displaydata(){
  return $identifier;
}

with

function displaydata(){
  return $_POST['DEPT'];
}

it accurately prints out the requested info.

Any clue what's going on here?

+7  A: 

You need to declare global $identifier in your function. PHP doesn't automatically look in the global scope for undefined variables outside of the superglobals.

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

Ian Wetherbee
Ahhh, that fixes everything! Thanks!
Kyle
Quick follow up. I know thatglobal $var;$var = SOMEDATA; is okay.Will:global $var = SOMEDATAwork?
Kyle
No, the global statement needs to be on its own line.
Ian Wetherbee
+1  A: 

As above said, make identifier variable global, or better yet pass $identifer as a parameter to the function. Globals in my experience make for hard debugging in larger applications. Generally speaking, there is usually a better approach than to just toss a global around.

Chris
Ahh, good point. Thanks!
Kyle
+2  A: 

In your code you have two $identifier variables. One is a local variable of displaydata(). The other $identifier, that is assigned the value of $_POST is outside the scope of the displaydata() function.

However $_POST is a superglobal. This means it is always available in all scopes. This is why this works:

<?php
function displaydata(){
    return $_POST['DEPT'];
}
?>

If you want to pass information to the local variables inside of displaydate, then use an argument:

<?php
displaydate($_POST['DEPT']);

function displaydata($identifier){
    return $identifier;    
}
?>

Although, in this case the scope of displaydata includes $_POST, since $_POST is a superglobal.

Peter Ajtai
Thanks man! Much appreciated
Kyle
A: 
<?php

    $identifier = $_POST['DEPT'];

    function displaydata($idefier){
      return $idefier;
    }
    displaydata($identifier);
    ?>

try this one. You have to pass the value to the function or declare $identifier as global

Dr Casper Black
Thanks man! Much appreciated
Kyle
+1  A: 

$identifier is in the local scope

stillstanding
Thanks man! Much appreciated
Kyle