0

I am not sure if this is possible, however, can we build a method that returns or echo the result based on calling the method directly or used in assignment

function foo()
{
    return "bar";
}

$abc = foo();
// $abc will have the value "bar"

But if foo() is called directly, it should echo "bar"

foo();
// should echo / print "bar"

adding echo before foo() solves the problem, but how could this be achieved without using echo. Probably adding some line of code to the function foo()

4
  • 2
    Method itself has no idea how it will be used in outer scope (it may be in expression, in single call, in assignment or even in some thing like eval() ) Commented Jan 29, 2014 at 6:50
  • @AlmaDo, thanks! however, there should be something i can manage the default method behaviour based on how it is called Commented Jan 29, 2014 at 6:52
  • You can pass some parameter to function for decide functionality Commented Jan 29, 2014 at 6:56
  • Ok. Good luck with $x = function() { return call_user_func(chr(102).str_repeat('o', 2)); }; eval('echo $x();'); Commented Jan 29, 2014 at 6:58

1 Answer 1

1

There is a possible way is to echo inside your function . Just like

<?php function foo()
{
    echo "bar";
    return "bar";
}

 echo $abc = foo();
?>
Sign up to request clarification or add additional context in comments.

1 Comment

this would not work. if we use $abc = foo(); to get value into $abc, it would echo the value as well.

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.