Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Can a function know if it's being assigned as a value?

Tags:

function

php

In other words, can fn() know that it is being used as $var = fn(); rather than as fn();?

A use case would be to echo the return value in the latter case but to return it in the former.

Can this be done without passing a parameter to the function to declare which way it is being used?

like image 246
eyelidlessness Avatar asked Dec 17 '22 10:12

eyelidlessness


1 Answers

Many PHP functions do this by passing a boolean value called $return which returns the value if $return is true, or prints the value if $return is false. A couple of examples are print_r() and highlight_file().

So your function would look like this:

function fn($return=false) {
    if ($return) {
        return 'blah';
    } else {
        echo 'blah';
    }
}

Any other way will not be good programming style.

like image 144
Paige Ruten Avatar answered Jan 07 '23 02:01

Paige Ruten