About variables - A best practice question

Discussion in 'PHP' started by neha2011, May 11, 2011.

  1. #1
    Hello all,

    I've just found out that, we can store other things then values on variables; OR, that "value", actually, means more then I was expecting to mean.

    On the following excerpt:
    $fieldsAreFilled = (!empty($hostNameInput) && !empty($hostAddressInput));
    $hostInfoEqualsInput = ($hostNameInfo == $hostNameInput && $hostAddressInfo == $hostAddressInput);
    
    if ($fieldsAreFilled && !$hostInfoEqualsInput) {
        ...
    } 
    
    PHP:
    We are storing a "condition" into a variable?
    Is there a name for this kind of operation, so that we can learn more about it?
     
    neha2011, May 11, 2011 IP
  2. ker

    ker Peon

    Messages:
    97
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    0
    #2
    No, You cannot store condition into variable!
    I have to mention that or, and, equals (||, &&, ==) are binary operators ("functions"). So, when php interpreter comes to following line:
    hostInfoEqualsInput = ($hostNameInfo == $hostNameInput && $hostAddressInfo == $hostAddressInput);
    PHP:
    he tests if $hostNameInfo equals $hostNameInput and $hostAddressInfo equals $hostAddressInput. I both conditions are true, then hostInfoEqualsInput stores just one boolean - true, else hostInfoEqualsInput stores false.
    When you call hostInfoEqualsInput on some other place, condition is not checking again.
     
    ker, May 11, 2011 IP
  3. JoelLarson

    JoelLarson Peon

    Messages:
    61
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I've never tested code like your example, so I'm not sure if it works or not. What I do know for sure though is the closest syntax to what you have would be short-hand if statements:

    $hostInfoEqualsInput = ($hostNameInfo == $hostNameInput && $hostAddressInfo == $hostAddressInput) ? TRUE : FALSE;
    PHP:
     
    JoelLarson, May 13, 2011 IP
  4. hyperboards

    hyperboards Peon

    Messages:
    16
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    neha2011, it is as ker has said, you are not storing the conditional statement, you are storing the result form the conditional statement.

    What JoelLarson is referring to is a ternary operator and is also very useful if you want to look that up.
     
    hyperboards, May 13, 2011 IP