简体   繁体   中英

what is the purpose of setting variables to empty (“ ”) after defining them?

Im learning about validating form input data and there was this bit of code on w3schools that i don't understand. see below:

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

//bla bla bla

i dont understand what "// define variables and set to empty values" means.

Don't use this tutorial. I'm looking at this test_input() function and can't believe that someone would publish this code:

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

See my answer here for more information on why this is a bad idea, and what to do instead: https://stackoverflow.com/a/7810880/362536

Now, on to your actual question. In many languages, you are required to declare what variables you are going to use before you use them. PHP is not one of these languages. Some people think that your code is easier to read if you know what all the variables are up front, and will define these variables as a matter of code style. That is, they will list variables and set them to some value. The code you have:

$nameErr = $emailErr = $genderErr = $websiteErr = "";

... is functionally equivalent to:

$nameErr = '';
$emailErr = '';
$genderErr = '';
$websiteErr = '';

In PHP, you can chain your variable assignments, which is why these two are equivalent.

If you choose to declare your variables as a matter of style, you should not assign an empty string to them. You should use null instead. Suppose I have a variable that is conditionally assigned data from a user input field. If I use empty string '' to initialize variables, I have no way of knowing if the form field existed and was submitted or not. If I use null , I can then use isset() to determine if the variable has an empty form field (empty string '' ) or null as its value.

You may very well decide that empty string initialization is right for your application. As John Conde says in the comments above, many folks use this so they can freely concatenate variables without worrying about what's in them, as even if they don't get an explicit value assigned, you already assigned an empty string. I would argue that there is rarely a time when you will work with data that always maintains a single purpose throughout it's lifetime, and that it's best to have data in the cleanest representation as possible. If a variable is intended to be null , its value should indeed be null and not an empty string. What you choose is up to you and your specific circumstances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM