Throwing out Var from inside a function gives meaningless 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 quanundrum is explicitly implied, but even then I will formulate this problem to the best of my ability.

Wth?

Variables are initialized at the very beginning of the script, but half of my var_dumps returns NULL

Why?

+4
source share
6 answers

You are trying to access variables from scope. $ name, $ url and $ active are declared outside the addSponsor function; thus, the function thinks that you are creating new variables and initializing them with null values.

+1
source

To access these variables from a function (without passing them as arguments), you will need to use the global 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 variables 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

+2
source

If you need, you can do this:

 function addSponsor() { global $name, $url, $active; var_dump($name); var_dump($url); var_dump($active); } 

But global variables are bad. I would rewrite your script as follows:

 $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); } } 
+2
source

The addSponsor() function calls var_dump in what it sees as NULL , because the variables you are trying to get are in the global scope. this page explains it pretty well.

+1
source

If you want to use these var in your function, you must declare them global:

 function addSponsor() { global $name, $url, $active; var_dump($name); var_dump($url); var_dump($active); } 
+1
source

To make reading easier, I highly recommend encoding the utility function, for example:

 function DumpVar($obj) { echo "<pre>"; var_dump($obj); echo "</pre>"; } 

Also note that using output buffering ( ob_start , etc.) is nice, but var_dump may be messed up; what to see if you are on a page in the ob structure. I came across this because of trying to capture the var_dump string in the output buffer for JSON data, which would be dislpayed in alert (). You can solve it, but keep this in mind. An example of a successful ob HTML approach is in the comment here .

-1
source

All Articles