Haryono Sariputra Haryono Sariputra - 6 months ago 13
PHP Question

What is the meaning of return empty statement in PHP Function

Sorry before,
maybe this is a very very basic question, but i really do not have an idea with this statement. Here the code, Thanks before :D

Class Trying{
public function theFunction(){
if (get_class($this) == __CLASS__) return;
}
}
$try = new Trying();
$try->theFunction();

Answer

When a function is called you are asking the function to do something and return the result. When a function ends, it will return null unless told otherwise.

What your function is doing:

{
    Am I this class? Return null;
    Return null; //end of function. Does this automatically.
}

To be useful the return value needs to be specified, e.g.

{
    Am I this class? return true;
    Otherwise, return false;
}

The value of this return will then be the answer (true or false).

Starting with your code:

public function theFunction(){
    if (get_class($this) == __CLASS__) return;
}

becomes:

public function theFunction(){
    if (get_class($this) == __CLASS__) {
        return true;
    }
    return false;
}

which can be refactored into:

/**
 * Am I this class?
 * @return Boolean
 */
public function theFunction(){
    return (get_class($this) == __CLASS__);
}
Comments