I\'ve been coding personal scripts for years in PHP and get used to turn off Error display. I\'m about to release some of these scripts and would like to do it the proper way.
I posted this in a comment earlier, but someone suggested I submit it as an answer.
The shortest and simplest way I can think of, is to do:
$foo = $bar = $ping = $pong = '';
I often prefer to set things to false, instead of an empty string, so that you can always do checks in the future with === false, but that is just a preference and depends on how you are using these variables and for what.
Why not just set them?
<?php
$foo = '';
$bar = '';
//etc
?>
If you're trying to preserve the value in them, then yes that's the correct way in general. Note that you don't need the second pair of brackets in your statements:
if (!isset($foo)) $foo = '';
is enough.
In OOP you can use this approach:
protected $password, $full_name, $email;
For non-OOP you declare them just in code they will be Undefined if you didn't assign any value to them:
$foo; $bar; $baz;
$set_foo = (isset($foo)) ? $foo : $foo = 'Foo';
echo $set_foo;
A somewhat round-about way of doing this is if you put the name of your variables in an array, and then loop them with a Ternary Operator, similar to powtac
's answer.
$vars = array('foo', 'bar', 'ping', 'pong');
$defaultVar = '';
foreach($vars as $var)
{
$$var = isset($$var) ? $$var : $defaultVar;
}
As mentioned in other answers, since version 5.3, PHP allows you to write the above code as follows:
$vars = array('foo', 'bar', 'ping', 'pong');
$defaultVar = '';
foreach($vars as $var)
{
$$var = isset($$var) ?: $defaultVar;
}
Note the changed Ternary Operator.
<?php
$foo = $bar = $ping = $pong = '';
?>
If it's your script and you know which variables where you use, why you want spend resourses to check if the variable was declared befor?
Your if()
with isset()
attempt is the proper way of doing that!
But you can write it a little bit shorter/more readable, using the Ternary Operator:
$foo = isset($foo) ? $foo : '';
The first $foo
will be set to the value after the ?
when the condition after the =
is true, else it will be set to the value after the :
. The condition (between =
and ?
) will always be casted as boolean.
Since PHP 5.3 you can write it even shorter:
$foo = isset($foo) ?: '';
This will set $foo
to TRUE
or FALSE
(depending on what isset()
returns), as pointed by @Decent Dabbler in the comments. Removing isset()
will set it to ''
but it will also throw an undefined variable notice (not in production though).
Since PHP 7 you can use a null coalesce operator:
$foo = $foo ?? '';
This won't throw any error, but it will evaluate as TRUE
if $foo
exists and is empty, as opposed to the shorthand ternary operator, that will evaluate as FALSE
if the variable is empty.