0

Possible Duplicate:
Reference - What does this symbol mean in PHP?

When I use a function I use standard return statements.

I mean by that that I usually either return true or false or a variable. Nevertheless I am currently following a tutorial which I understand pretty well beside the return of the here below function.

I do not get how to read the question mark the two dots....

public function someFunction()
{
    return null === $this->anAttribute ? null : $this->aFunction();
}
Community
  • 1
  • 1
Marc
  • 7,909
  • 18
  • 63
  • 84

3 Answers3

2

Return null if $this->anAttribute is null else return $this->aFunction()

?: called ternary operator

Writing null in first place is used for avoiding wrong assignments typo, like if ($a = null). If you get used to writing functions and constants firts this will lead to error if(null = $a)

=== can be read in article used above and called Identical. $a === $b TRUE if $a is equal to $b, and they are of the same type.

Artem L
  • 9,115
  • 1
  • 18
  • 14
1

It will return null if $this->anAttribute is strictly null, otherwise, it will call $this->aFunction() and return the result of this function (if the function made a return at the end)

j0k
  • 21,914
  • 28
  • 75
  • 84
1

It is a ternary operator. The stuff on the left is an expression (like if (...)). The next value is used if the expression evaluates to true, and the last value is used if the expression evaluates to false:

expression ? true : false;

In pseudocode you could write it like this:

if expression is true:
    use this
otherwise:
    use this

It is often easier to read ternary code if you use parenthesis around it (it is a subtle thing, but when you see a return statement that begins with a parenthesis you know that you should stop and read it properly, instead of either ignoring it or getting stumped for a while and then realize what it is).

return ((null === $this->anAttribute) ? null : $this->aFunction());
Sverri M. Olsen
  • 12,362
  • 3
  • 32
  • 50
  • thank you Sverri. By the way do you know why the syntax doesn't start with return $this->anAttribute === null instead of return null === $this->anAttribute ? – Marc Dec 26 '12 at 10:50
  • Well, it does not matter which way you compare the two values. It is like the mathematical equation `4 + 1 = 5`. You can also write it `5 = 4 + 1` and you get the same result. Because of PHP's assignment operator, `=`, some people like to put `null` (and other language constants that cannot be overridden, such as `true` and `false`) first, just in case they mistakenly write `=` instead of `==` or `===`. – Sverri M. Olsen Dec 26 '12 at 16:13