Var dump called from within a function gives nonsensical results
$name = $_POST["name"];
$url = $_POST["url"];
$active = $_POST["active"];
if($action == "add")
{
var_dump($name); // Returns: String(10) "..."
var_dump($url); // Returns: String(27) "..."
var_dump($active); // Returns: String(2) "..."
addSponsor(); // Returns: NULL NULL NULL
}
function addSponsor()
{
var_dump($name);
var_dump($url);
var_dump($active);
}
I think the quanundrum is self-implied, but even so I'll formulate this problem to the best of my ability.
WTH?
Variable开发者_JAVA技巧s are initialized at the very start of the script, yet half of my var_dumps return NULL
Why?
If you must, you can do this:
function addSponsor() {
global $name, $url, $active;
var_dump($name);
var_dump($url);
var_dump($active);
}
But global variables are bad form. I would rewrite your script like so:
$post_vars = array(
'name' => $_POST["name"],
'url' => $_POST["url"],
'active' => $_POST["active"]
);
if ($action === "add") {
foreach ($post_vars as $post_var) {
var_dump($post_var);
}
addSponsor($post_vars);
}
function addSponsor($post_vars = array()) {
foreach ($post_vars as $post_var) {
var_dump($post_var);
}
}
To access those variables from within the function (without passing them in as arguments) you will need to use the global
keyword to tell PHP that they have been declared in the global scope:
function addSponsor()
{
global $name, $url, $active;
var_dump($name);
var_dump($url);
var_dump($active);
}
I would suggest specifying formal parameters, and passing the variables in as arguments to the function:
function addSponsor($name, $url, $active)
{
var_dump($name);
var_dump($url);
var_dump($active);
}
See http://php.net/manual/en/language.variables.scope.php
You're trying to access variables out of scope. $name, $url, and $active are declared outside of addSponsor function; thus, the function thinks you're creating new variables and initializes them to null.
the addSponsor()
function is calling var_dump
on what it sees as NULL
because the variables you are trying to access are in the global scope. this page explains it pretty well.
If you want to use these vars in your function you have to declare them global:
function addSponsor()
{
global $name, $url, $active;
var_dump($name);
var_dump($url);
var_dump($active);
}
To make things easier to read, I'd highly advise coding a utility function like:
function DumpVar($obj) {
echo "<pre>";
var_dump($obj);
echo "</pre>";
}
Also, please note that using output buffering (ob_start, etc) is nice, but can be messed up by var_dump; something to watch for if you're in a page within an ob structure. I ran into that because of trying to capture a var_dump string in an output buffer for the JSON data to be dislpayed in an alert(). You'll be able to resolve it, but keep it in mind. An example of a successful ob HTML approach is in the comment here.
精彩评论