开发者

PHP will echo $_POST data, but won't let me store it

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?开发者_StackOverflow社区


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


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.


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.


$identifier is in the local scope


<?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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜