Re: Setting & displaying Variables [message #182862 is a reply to message #182859] |
Sat, 21 September 2013 20:47 |
Richard Damon
Messages: 58 Registered: August 2011
Karma:
|
Member |
|
|
On 9/21/13 4:20 PM, 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.
>
> // echo strlen($comments); // GETS Notice: Undefined variable: comments
> in C:\xampp\htdocs... and nothing displays.
>
> echo $_POST["comments"]; // WORKS
> //echo $comments; // GETS Notice: Undefined variable: comments in C
> ... and nothing displays.
>
> </code>
> ===================
>
> I'm obviously missing something here since it appears the var is set
> according to the 2 statements that do display what I expected. Can you
> straighten me out? I've had this happen before with other vars and it's
> always confusing.
>
> TIA,
>
> Twayne`
>
>
As others have commented on, not showing us the full code makes it very
hard to help. The error message you are quoting says that the variable
does NOT at that point have a value assigned to it.
You say that the variables have to be defined for the echo statements to
work, but then you also say that you get the error because they are not
defined.
Note that PHP is not like more strictly declared languages, you do not
need to "create" variables explicitly to use them, they will be created
as needed. Thus a script like:
<?php
echo $comment
?>
will "work" in the sense that the PHP language defines what it will
generate, which includes a possible "Notice" due to using the value of a
variable that was never set, and thus is possibly wrong, but is defined
(which is the reason it is just a NOTICE, one of the lower levels of
messages defined).
Another comment is your "WORKS but not needed, done elsewhere"
statement, that might be refering to the now obsolete functionality of
inserting into the global variable space the contents of some of the
"super-globals" like $_POST. Older version of PHP would default to this
behavior, later ones defaulted to not doing this behavior, and the
latest version (if I remember right), no longer have the option to do
this behavior (except via explicit script code). If you script depended
on this behavior, and was moved or the server upgraded, then it could
break for this reason.
|
|
|