64

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.

The only reason why I turn off error display is to avoid having to test every single var, prior using it, thanks to isset().

So, here is my question:

Is there a better way to declare multiple vars than this ?

<?php
  // at the begining of my main file
  if (!isset($foo))  ($foo = '');
  if (!isset($bar))  ($bar = '');
  if (!isset($ping)) ($ping = '');
  if (!isset($pong)) ($pong = '');
  // etc. for every single var
?>

Something like this for instance :

<?php
  var $foo, $bar, $ping, $pong;
?>
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Tom Biakryek
  • 641
  • 1
  • 5
  • 3
  • 3
    Expecting `var $foo` to be an empty string seems strange. What operations are you doing later that's causing problems? – Mike B Jun 14 '12 at 00:35
  • 2
    I don't quite understand what this is about. You're testing a variable before you set to check if you can set it? Are you coming from another language where you have to set variables like `dim d as Integer`? I think what you really need is some encapsulation like functions, classes, etc, so you're out of the global namespace, and then get in the habit of declaring variables at the head of each function/class method. – Jared Farrish Jun 14 '12 at 00:35
  • @MikeB: a simple test. If the var is not declared in first place, a simple `if ($foo == 'blabla')` will prompt an error. – Tom Biakryek Jun 14 '12 at 00:44
  • Where are the variables coming from then? Are you using something like `extract($_GET)` to create variables and you don't actually know what's been created? – Mike B Jun 14 '12 at 00:45
  • What does that error say? Is it a warning? – Jared Farrish Jun 14 '12 at 00:47
  • @JaredFarrish ` – Mike B Jun 14 '12 at 00:48
  • @JaredFarrish: the point is that I do not need functions there. The only reason why I'd like to test these vars is to avoid to get an error displayed on servers where error reporting is not turned off. The script works as is (and displays no php related errors nor is weak from a security point of view). – Tom Biakryek Jun 14 '12 at 00:48
  • @JaredFarrish yes, it's only a warning (sorry if it was not clear) – Tom Biakryek Jun 14 '12 at 00:50
  • Then leave it to the people running the script, or (if they're not savvy) put `error_reporting(0)`. A notice is not anything to pepper your code with frivolous checks over, and you should still be using functions at least so that you are not in the global namespace (which is I thought you may be concerned). It's just good practice to encapsulate your code in some way. If you're really worried, just declare your variables you've used at the head of the script. No checks necessary, and many consider this a good self-documenting practice to get in anyways. – Jared Farrish Jun 14 '12 at 00:52
  • [E_NOTICE - Run-time notices. Indicate that the script encountered something that could indicate an error, but *could also happen in the normal course of running a script*.](http://us.php.net/manual/en/errorfunc.constants.php) – Jared Farrish Jun 14 '12 at 00:53
  • "A notice is not anything to pepper your with frivolous checks over" Thanks for your answer, that's actually what I was worried about "is that considered as a bad practice to force the error_reporting to be set to 0?". Now I have an answer. Would you have any links regarding code encapsulation ? As stated before, to date, I only use functions or class when it's absolutely required. An since I'm self-taught, I'm really interested in any lecture that could improve my skills. – Tom Biakryek Jun 14 '12 at 01:00
  • @TomBiakryek No no no, wrong takeaway :p - Error checking is definitely a good thing. Many advocate error reporting be set to its strictest levels during development (and of course off on production). Your intentions in this question are very good practice. I was just curious about your particular circumstance. – Mike B Jun 14 '12 at 01:03
  • About `error_reporting(0)`, which disables all PHP errors, it's a common security practice to enforce disabling errors for security purposes. So using it, yes, except in development (and preferably in a private environment or part of your site). Now, in a script you're handing off, that depends on the skill levels of the person you're giving it to, so you have to consider that they may not know how to, but should have it disabled in production. – Jared Farrish Jun 14 '12 at 01:05
  • Read this question for more info about error reporting http://stackoverflow.com/questions/74847/what-is-the-recommended-error-reporting-setting-for-development-what-about-e – Mike B Jun 14 '12 at 01:05
  • As for encapsulation, see [What is the purpose of encapsulation?](http://stackoverflow.com/questions/3644321/php-what-is-the-purpose-of-encapsulation) [What is encapsulation with simple example in php?](http://stackoverflow.com/questions/985298/what-is-encapsulation-with-simple-example-in-php) There really isn't any "really needed" time for encapsulation techniques, it's just about it being appropriate to your code's requirements. Some languages are almost entire functional or object-oriented, for instance. PHP gives you both worlds, so *try to use them as much as possible*. `;)` – Jared Farrish Jun 14 '12 at 01:07
  • This looks like a decent primer: [Encapsulation in PHP](http://wshell.wordpress.com/2009/10/12/encapsulation-in-php/) – Jared Farrish Jun 14 '12 at 01:17
  • @Helloall - Shall I declare like this `global $var1, $var2, $var3;` and `return $var1, $var2, $var3;`. Sorry didn't try in local just needed a quick answer with additional knowledge..So posting here..please don't mind! – Neocortex Dec 24 '13 at 13:54

7 Answers7

106
<?php
  $foo = $bar = $ping = $pong = '';
?>

If it's your script and you know which variables where you use, why you want spend recourses to check if the variable was declared before?

Pikamander2
  • 7,332
  • 3
  • 48
  • 69
DaneSoul
  • 4,491
  • 3
  • 21
  • 37
  • 14
    Also, if you just want to "declare" them for some reason, you can put them all on one line with `;`, as in `$foo; $bar; $far; $boo;`, all on one line. Note for the uninitiated, `$foo, $bar, $far, $boo;` throws an (parse) syntax error, killing the script. – Jared Farrish Jun 14 '12 at 01:21
  • 1
    @JaredFarrish `$foo; $bar; $far; $boo;` will still throw `Notice: Undefined variable: ...` – Jeff Puckett Jul 19 '16 at 16:46
  • 1
    Will this not make all values change if you change the value of only one variable? – molerat Jul 13 '18 at 09:31
  • 3
    molerat, NO, after the variables are declared you can change them separately and each one will keep it's own value. – DaneSoul Jul 14 '18 at 17:18
  • @molerat you program in python too, dont u?? i just started programming in python and found out the hard way that changing one in the chain changes all the others. actually, wait, it wasnt python. it was another language – oldboy Nov 11 '18 at 23:00
  • is it possible to declare the array as the same format `$foo = $bar = $ping = $pong = [ ];` – ManojKiran A Apr 01 '19 at 12:28
14

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.

lpd
  • 2,151
  • 21
  • 29
pocketfullofcheese
  • 8,427
  • 9
  • 41
  • 57
8

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.

Chazy Chaz
  • 1,781
  • 3
  • 29
  • 48
powtac
  • 40,542
  • 28
  • 115
  • 170
  • 1
    Honest question, why would you want to have `$foo` be an empty string vs null? I'm going in circles trying to come up with a circumstance – Mike B Jun 14 '12 at 00:38
  • I'm sure the questioner simply wants to set an default value, in this case an empty string. And keep in mind '' != NULL or not set ;-) – powtac Jun 14 '12 at 00:39
  • I don't know, I'm with @MikeB, I've been a recovering PHP developer going on eight years and I've never systematically done anything like this, or had a problem not doing it? – Jared Farrish Jun 14 '12 at 00:41
  • 6
    `$foo = isset($foo) ?: '';` will not do what you think it will do. If `$foo` is set, it will assign `true` to `$foo` regardless of `$foo`'s initial value. – Decent Dabbler Jun 14 '12 at 04:17
5

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.

Connor Deckers
  • 2,447
  • 4
  • 26
  • 45
2

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;
mbougarne
  • 91
  • 1
  • 4
0

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.

jli
  • 6,523
  • 2
  • 29
  • 37
-3

To fix the issue of

  <?php
  $foo = $bar = $ping = $pong = '';
  ?>

throwing

Notice: Undefined variable: ...

  <?php
  @$foo = $bar = $ping = $pong = '';
  ?>

It will not fix it but it will not be shown nd will not stop the script from parsing.

c0d3x1337
  • 47
  • 11
  • 1
    suppressing errors/notices/warning isn't the same as fixing them and this practice should be avoided. – treyBake Jun 21 '19 at 15:34