tags:

views:

80

answers:

6

I need to edit a function, but I cant figure out what the ? and the : false mean in the return statement. I think the : is an OR but the ? I dont know.

public function hasPermission($name) { return $this->getVjGuardADUser() ? $this->getVjGuardADUser()->hasPermission($name) : false; }

Anyone that can clear this up for me?

+8  A: 

It is PHP's Ternary Operator. It's like a shorthand for if/else expressions.

Your expanded code could look like so:

public function hasPermission($name)
{ 
    if ($this->getVjGuardADUser()) {
        return $this->getVjGuardADUser()->hasPermission($name)
    } else {
        return false;
    }
}

Some sample-code from php.net:

// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}
Benjamin Cremer
Thank you, that seems like a good operator to know, currently I have lots of those "expanded" if statements in my own code. Nice to know you can "clean" that up using this operator.
iggnition
I really wish they would approve the ifsetor()-operator (http://wiki.php.net/rfc/ifsetor).
Benjamin Cremer
+5  A: 

It's the ternary operator, a simple oneliner if then construct.

fabrik
+2  A: 

This is the ternary operator. It's documented here.

It's a short form for:

public function hasPermission($name) {
    if ($this->getVjGuardADUser()) {
        return $this->getVjGuardADUser()->hasPermission($name)
    } else {}
        return false;
    }
}

I recommend the more verbose style for conditional statements for better readability, though.

Techpriester
+1  A: 

It's called the ternary operator.

variable = predicate ? /* predicate is true */ : /* predicate is false */;

In your code, it's a shorthand form of the following:

if($this->getVjGuardADUser())
    return $this->getVjGuardADUser()->hasPermission($name);
else
    return false;
Giu
A: 

It's a ternaire expression.

You can replace this by:

if ($this->getVjGuardADUser())
 return $this->getVjGuardADUser()->hasPermission($name);
return false;
Kiva