1

so I have 2 functions like this:

function boo(){
  return "boo";
}

and

function foo(){
  echo "foo";
}

the fist one will return a value, and the 2nd one will output something to the screen directly.

$var = boo();
foo();

How can I merge these 2 functions into one, and somehow detect if it's being called to output the result to the screen, or if it's called for getting the return value? Then choose to use return or echo...

4 Answers 4

3
function boo_or_foo ($output = false) {
    if ($output) {
        echo "fbo";
    } else {
        return "foo";
    }
}

But whats the benefit against just using one function (boo()) and echo it yourself?

echo $boo();
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I was hoping there was a better way :) Something more elegant than adding a extra variable
1

Well, a function should only do one thing, so typically you would have two functions. But, if you would like to combine them you can just check if is set:

function boo($var=null){
  if(isset($var)) echo $var
  else return "boo";
}

Comments

1

well return true in the function that prints then yo just do

function foo(){
  echo "foo";
  return true;
}

    if(foo()){
    echo "foo did print something";
    }else{
    echo "nope foo is broken";
    }

Comments

1

I wanted to achieve the same effect. In my case I have functions that produce HTML which I want echoed directly sometimes (when an Ajax call is being made), or returned (when a call is made from another script).

For example, a function that creates a list of HTML <option> elements - listOfOption($filter). When one of my pages is first created, the function is called and the result is echoed in place:

<?= listOfOption($var) ?>

But sometimes the same data needs to be retrieved in an Ajax call:

http://site.com/listOfOption.php?parameter=2

Instead of writing two different scripts or specifying the behaviour in a parameter, I keep listOfOption($filter) in its own file like this:

if (__FILE__ == $_SERVER['SCRIPT_FILENAME'])
{
    echo listOfOption($_REQUEST['parameter']);
}

function listOfOption($filter)
{
    return '<option value="1">Foo</option>';
}

This way if the call is from another script, it returns the data; otherwise it prints the data.

Note that if a parameter isn't passed to the function I wouldn't have to do this, I could live with echoing the data always and replacing the <?= listOfOption() ?> invocation with <? listOfOption() ?> to keep things clear.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.