开发者

Cant figure out operators in php statement

I need to edit开发者_JS百科 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?


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'];
}


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


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.


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;


It's a ternaire expression.

You can replace this by:

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


It's a ternaire operator. Read more about it here:

  • http://www.lizjamieson.co.uk/2007/08/20/short-if-statement-in-php/
  • http://www.scottklarr.com/topic/76/ternary-php-short-hand-ifelse-statement/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜