views:

367

answers:

6

I was just looking at this code and i don't understand what RETURN TRUE does or what the point of it is? Can someone please explain?

class Elephpant {

    public $colour;

    public function dance() {
        echo "elephpant dances!\n";
        return true;
    }
}

Thankyou in advance ;-)

+5  A: 

In that specific piece of code - not very much.

In general however it would be used to return a condition of a validation or code that needs to return either a positive or a negative.

For instance, one would do the following:

public function isValidEmail($email) {
    // do work to see if email is valid
    if(/* Condition making it true */)
       return true;
    else
       return false;
}
Kyle Rozendo
Uargh! How about `return $isvalid;`?
Mef
@Mef - made the example clearer.
Kyle Rozendo
@Kyle The remark by @Mef still holds. In this case `return /* Condition making it true */;` would do the same.
Tom Lokhorst
@Tom - Never denied that, I was simply being overly specific
Kyle Rozendo
+10  A: 

It returns the boolean TRUE to whatever called dance(). That's all.

You would have to look at the consuming code to see if it makes something from it.

Gordon
Can you elaborate some possible example of such a consuming code? I have tried and fail
Col. Shrapnel
@Shrapnel $hasDanced = $elephpant->dance();
Gordon
...and exit from the function/loop
DaNieL
+1  A: 

Logically, returns boolean TRUE, but in this case doesn't make any sense since it'll return TRUE anyways.

Kemo
Not true. A function without a return statement returns `null`, not `true`.
Pekka
@Pekka **this** function return TRUE anyways. Therefore, in this case doesn't make any sense
Col. Shrapnel
Agree with @Pekka, not really sure what you are saying @Col. Shrapnel
Lizard
@Lizard you guys scaring me. There is no difference in **this particular function**. Not "a function", but this function. The OP asked about this one. In this one it doesn't make any sense
Col. Shrapnel
@Col. Shrapnel: i thought the OP asked about how the `return` method works, and posted THAT function as an example. However i can be totally wrong.
DaNieL
@Pekka @Lizard I said "but in this case" and OP said "I was just looking at this code", so I probably ment this case in particular
Kemo
+1  A: 

Sometimes a method/function returns a boolean value to indicate if the operation was succesfull. In the given example it always returns "TRUE".

The calling code can then act upon succesfull completion of the code

if(dance()) echo "succes" else echo "fails"

Jasper
+1  A: 

You can read more about return here: http://www.php.net/return

There are few interesting applications of return like returning value from include-d file.

Kamil Szot
+1  A: 

because it's TRUE, elephpant does dance ;)

Sirber