norr norr - 5 months ago 29
PHP Question

Simplest way for return/echo in function (shorthand IF)

I have this function in my class. Default it should echo value, but also return value to variable by using optional parameter.

public function test($return = false) {

$value = 'demo123';

if ($return) {
return $value; // optional
} else {
echo $value; // default
}

}


Is there any way to make this "if" shorter, in one line (because I have a lot of functions with this so I can save many lines).

I tried ternary operators, but I don't know if I can use them in this somehow.

What's the best, correct, beauty way to do this return/echo function?

Answer

Lines are not expensive, so reducing lines of code is not a particularly useful goal, especially if it reduces readability.

However, you can remove the else clause, as return will, well, return!

public function test($return = false)
{
    $value = 'demo123';

    if ($return) {
        return $value; // optional
    }
    echo $value; // default
}
Comments