Jump to content

undefine constant


sungpeng

Recommended Posts

Use mysqli or PDO for your database work, as suggested.

 

With that said---, as Jacques pointed out, in PHP variables have a $ at the beginning.

 

Strings are delimited in one of two ways:

 

$foo = 'This is a string constant';
$fruit = 'banana';

$bar = "Double quotes will interpolate (inject the value at runtime) of any variables into the string.  See I am eating a $fruit";
Now if I have an array with associative (string named) keys, those keys should be string constants in most cases.

 

$row['name'] = 'Bob';
$row['contact'] = "bob@host.xyz";
So what If I want to use interpolation, and output the values of the 2 keys in my output. You may have found this is an issue:

 

$row['name'] = 'Bob';
$row['contact'] = "bob@host.xyz";
echo "You can email $row['name'] here:  $row['contact']."
// Oops PHP doesn't like this....

PHP won't allow you to do this for some reason. You get the dreaded:

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in ...

 

Process exited with code 255.

 

What it will allow you to do is this:

 

echo "You can email $row[name] here:  $row[contact]."
// Works ok.
What PHP does, is first check to see if there is a constant by that name, and then if not found, will see if used as a string, there is a key that matches in that array.

 

This is a case of PHP trying to be helpful, when perhaps it shouldn't. In the process however, it will issues a warning, which is NOT an error. Warnings are very helpful for development, but often in production there are warnings and information that will only fill up your logs, so in production people often choose to suppress those warnings and informational messages. Check out the error_reporting page for more on this topic: http://php.net/manual/en/function.error-reporting.php

 

As it turns out, there is a workaround that allows you to interpolate array variables with the associative key names delimited as string constants. This is how you should do it, and will make this issue essentially go away for you:

 

echo "You can email {$row['name']} here:  {$row['contact']}.";
Here's a 3v4l.org snippet.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.