简体   繁体   中英

php variable assign as false value

class Email
{       
    var $to = false;
    var $subject = false;   
}

I am a beginner in PHP. I have a class Email . In that class my variable $to gets assigned to false initially. It will be assigned to a value that is storred in another variable. I don't understand why this variable has this initial false value.

Can you please explain me why

It's usually a good idea to give variables a default value. That way, if the variable is used before it's reassigned, it will have a predictable value. false and null are useful initial values, as they can be distinguished easily from the values that will be assigned to the variables later.

false should generally only be used for variables that will hold boolean true / false values. For other variables, null is a better choice as a default. But this is mostly just a stylistic choice, either will usually work.

It's good to initialize your variables for predictability. For example:

foreach($stuff as $thing){
   $myVar[]=$thing;
}
doSomething($myVar);

If for whatever reason $stuff is empty (but hopefully still an array), $myVar will not exist after the loop and thus doSomething() will receive null as parameter instead of an array , resulting in at least a warning in your error log.

For functions/methods there's a similar reason:

function myFunc($stuff){
   $result=null;
   if($stuff==true)
       $result=array(1,2,3);
   return $result;
}

This may seem nice, because you've initialized your $result variable like a good student. But if $stuff!=true , $result will be null instead of an array . That may not seem much of a problem, but all the code that's using the myFunc() function will now have to be able to handle arrays AND null values (usually that means having to write unnecessary if() clauses for type checking).

Whereas if myFunc() always returned arrays (easily possible by initializing $result as array() instead), you have one less thing to worry about.

I kind of side-stepped your question, but hopefully this will still help you understand the concept.

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