Reputation:
I have a variable that sometimes doesn't exist that I want to use inside of a string (or heredocs).
My code is like this:
if(someExternalThings()) {
$variable = 'value';
}
echo "I have a {$variable}";
The code works fine when someExternalThings()
is true, but if it doesn't, PHP throws an error, as expected.
Since I know that variable won't break anything (other than inside of the strings) I decided to add @
before it.
echo "I have a {@$variable}";
But it outputs: I have a {@}
and throws an error.
I fixed this by doing this:
$variable = @$variable;
echo "I have a {@$variable}"
//outputs: I have a {@} and throws no errors
Or by putting the entire echo
inside of the if that checks someExternalThings()
if(someExternalThings()) {
$variable = 'value';
echo "I have a {$variable}";
}
This kinda confuses me since we can use these...
echo "{$foo->bar[0]}";
echo "{${foo::bar}}";
...and it just works fine.
Upvotes: 0
Views: 60
Reputation: 35149
The use of '@' for 'silence errors' does not work for variables inside a string. It would work at the start of the statement, but it's much better to avoid the issue.
If you want to avoid an 'unknown variable' notice, you can set it to something. For example:
<?php
$variable = '';
if(someExternalThings()) {
$variable = 'value';
}
// now $variable always has a value, maybe empty, but it exists.
echo "I have a {$variable}";
If the echo should only happen when $variable has a value, then put it into the if
condition.
Upvotes: 1