Re: Setting & displaying Variables [message #182865 is a reply to message #182859] |
Sat, 21 September 2013 21:55 |
J.O. Aho
Messages: 194 Registered: September 2010
Karma:
|
Senior Member |
|
|
On 21/09/13 22:20, Twayne wrote:
> Hi,
>
> Obviously, the issue is around the comments var. It works, but it
> doesn't and I'm hoping someone can explain why.
>
> Both echo strlen($comments); and echo $comments; throw a Notice
> about an undefined variable. But the variable "comments" HAS to have
> been defined in order for the two echo statements to work!
> The variable 'comments' is also in SESSION data, which will also get
> the same Notice of an undefined variable.
>
> What the heck am I missing? Why do I get the undefined var in those two
> statements?
>
> ===================
> <code>
> echo strlen($_POST["comments"])."<br />"; //WORKS
>
> $commments = $_POST["comments"]; // WORKS but not needed; done elsewhere
> too.
Assuming this is just a typo and it was supposed to be $comment
> // echo strlen($comments); // GETS Notice: Undefined variable: comments
> in C:\xampp\htdocs... and nothing displays.
Variables ain't super global, with other words if you do something
inside a function it will not automatically be the same outside the function
$comment = "q";
function b() {
$comment = "b";
}
b();
echo $comment;
This will result in "q" and not "b", as the $comment inside the function
is another than the one outside the function.
just to clarify, values will not magically get into functions
$comment = "q";
function b() {
echo $comment;
}
b();
this will return an empty output (logging undefined variable).
There is a few exception from this, super global variable is one of
those, like $_POST, $_GET, $_SESSION and so on, thos can be accessed
anywhere in your code.
You can use global in a function to access variable set outside a
function (this is really bad coding and you will most likely get in bad
trouble, so avoid using it).
--
//Aho
|
|
|