user3260168
user3260168

Reputation: 1

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

Upvotes: 0

Views: 106

Answers (2)

DanMan
DanMan

Reputation: 11561

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.

Upvotes: 0

Barmar
Barmar

Reputation: 781721

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.

Upvotes: 3

Related Questions