0

I got PHP function like this:

function doingSomething($arg)
{
    ...
    echo($someString);
}

I don't want to copy/pase that function and make second one only if I need that function to return value, not echo it. How could I modify it so it will just return $someString whenever I need it?

1
  • If I add return it will do both. I just want to do "return" whenever I need insted of "echo". Commented Oct 2, 2013 at 11:22

3 Answers 3

3

Use another parameter to tell your function what to do with the string:

function doingSomething($someString, $echo = false){
    if($echo){
      echo $someString;
    } 
    return $someString;
}

Then if you want to echo it:

doingSomething('String to echo', true);

Or return:

doingSomething('String to return');
Sign up to request clarification or add additional context in comments.

7 Comments

Why not always return the string, but only echo it if there's a parameter set?
Because that's not what the OP asked?
@ScottHelme It doesn't matter if it returns anything or not if it's just called by doingSomething('string') any way.
Thanks anOG. Can it work like if I just put one arg in that function (I won't put second arg in that function) it will echo by default and if I put second arg: false it will return it?
I would have thought that the original would have made it a little easier to understand.
|
1

You can do this with a second parameter to the function.

function doSomething($arg, $doOutput) {
    ...
    if ($doOutput) { echo $someString; }
    else { return $someString; }
}

This will echo the String if $doOutput is true and return it otherwise.

Comments

1

Why not just either use or return the value as needed like this:

<?php
function doingSomething()
{
    return "Fluffeh";
}

$var=doingSomething();
echo $var."<br><br>";

echo "Or this way ".doingSomething();
?>

You get the best of both worlds, can either save the output into a variable or simply echo it out in your code as needed?

Output:

Fluffeh

Or this way Fluffeh

3 Comments

By default I will echo, only in very rare cases I will return it so I will save space by doing echo in that function by default.
The only other way is as the other two answers suggest, which is to pass another argument to the function each and every time. On that note though, saving space? I don't understand.
Yes I already got answer made by anOG and that is was I was looking for. As for saving space... well I will be calling that function with HTML code so it's easier for me to just put that function (without echo before it, and no, I don't want to save that function's String to another $var) so I know it will echo string... nevermind it's all good now :) Thanks to you all!

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.