I'm working with some functions that echo output. But I need their return so I can use them in PHP.
This works (seemingly without a hitch) but I wonder, is there a better way?
function getEcho( $function ) {
$getEcho = '';
ob_start();
$function;
$getEcho = ob_get_clean();
return $getEcho;
}
Example:
//some echo function
function myEcho() {
echo '1';
}
//use getEcho to store echo as variable
$myvar = getEcho(myEcho()); // '1'
no, the only way i can think of to "catch" echo-statements it to use output-buffering like you already do. i'm using a very similar function in my code:
function return_echo($func) {
ob_start();
$func;
return ob_get_clean();
}
it's just 2 lines shorter and does exactly the same.
Your first code is correct. Can be shortened though.
function getEcho($function) {
ob_start();
$function;
return ob_get_clean();
}
echo getEcho($function);
Your first piece of code is the only way.
Did you write these functions? You can go 3 ways:
Using your wrapper to do capturing via output buffering.
Extra set of functions calls, wordpress style, so that "somefunc()" does direct output, and "get_somefunc()" returns the output instead
Add an extra parameter to the functions to signal if they should output or return, much like print_r()'s flag.
function getEcho() {
ob_start();
myEcho();
return ob_get_clean();
}
$myvar = getEcho();
Related
I am using a Wordpress plugin for custom fields.
the_field('something')
is, I pressume, just echoing the return value.
Is it not possible to store that return value into a variable?
because $a = the_field('something'); is also echoing.
What I really want to do is this
if(the_field('something')) {
// echo the_field('something')
}
else
// do something
but either way, it just echoes that thing in the page
As I said in my comment, If a function just echos something, then there is no return value. But there is still a way to capture the output.
Consider this function
function doStuff()
{
echo 'hello';
}
You can't get a return value from that, but you can capture the contents by using the ob_functions:
ob_start();
doStuff();
$output = ob_get_contents();
ob_end_clean();
Now $output contains the output of that function, rather than it having been printed.
WordPress I do not like. It seems that they have two functions (or more) for retrieving about anything. One echos it the_title() and the other returns it get_title(). For this plugin this should work:
if($field = get_field('something')) {
echo $field;
}
else
// do something
}
If you run across something that echos and doesn't return a value and no corresponding function that does return something, then:
ob_start();
the_something();
$output = ob_get_clean();
// use $output
The following function is part of code written into the core of a plugin I am reverse engineering. The problem with it is that I need to do an str_replace on it and I cannot because it is already set to echo.
The function is.
function similar_posts($args = '') {
echo SimilarPosts::execute($args);
}
I call it in my pages using similar_posts(), but what I really need to do in my theme is call $related = similar_posts(), however that function is set to echo. How do I change that.
I tried this.
function get_similar_posts($args = '') {
SimilarPosts::execute($args);
}
But that did not produce any results.
function get_similar_posts($args = '') {
return (SimilarPosts::execute($args));
}
If you want to use the value SimilarPosts::execute ($args) returns, you'll need to use the keyword 'return' inside your get_similar_posts.
function get_similar_posts ($args = '') {
return SimilarPosts::execute($args);
}
If you are unable to change the definition of get_similar_posts there are ways to snatch the content printed by similar_posts even though it's "set to echo".
This can be accompished by using the Output Control Functions available in PHP.
function echo_hello_world () {
echo "hello world";
}
$printed_data = "";
ob_start ();
{
echo_hello_world ();
$printed_data = ob_get_contents ();
}
ob_end_clean ();
echo "echo_hello_world () printed '$printed_data'\n";
output
echo_hello_world () printed 'hello world'
Use return instead of echo.
So that you have:
return SimilarPosts::execute($args);
instead of:
echo SimilarPosts::execute($args);
Wrap the function inside another in which you use output buffering.
Done it..
function get_similar_posts($args = '') {
return SimilarPosts::execute($args);
}
and on the page get_similar_posts();
Should have thought of that.
return from the function:
function get_similar_posts($args = '') {
return SimilarPosts::execute($args);
}
I just simply want to create a function name with a string value.
Something like this:
$ns = 'test';
function $ns.'_this'(){}
test_this();
It of course throws an error.
I've tried with:
function {$ns}.'_this'
function {$ns.'_this'}
but no luck.
Any thoughts?
You can use create_function to create a function from provided string.
Example (php.net)
<?php
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
?>
This is not possible. If all you want to do is, to prefix all functions with some common string, maybe you want to use namespaces?
namespace foo {
function bar() {}
function rab() {}
function abr() {}
}
// access from global namespace is as follows:
namespace {
foo\bar(); foo\rab(); foo\abr();
}
file with function (somefile.php)
function outputFunctionCode($function_name)
{?>
function <?php echo $function_name ?>()
{
//your code
}
<?php }
file with code which "declares" the function:
ob_start();
include("somefile.php");
outputFunctionCode("myDynamicFunction");
$contents = ob_get_contents();
ob_end_clean();
$file = fopen("somefile2.php", "w");
fwrite($file,$contents);
fclose($file);
include("somefile2.php");
It is ugly, but then again, it is an extremely bad idea to declare functions with dynamic names.
using "eval" is not a good practice, but that may serve the purpose similar to your requirements sometimes.
<?php
$ns = 'test';
$funcName = $ns.'_this';
eval("function $funcName(){ echo 1;}");
test_this();
?>
Is this what you are looking for?
<?php
function foo($a) { print 'foo called'.$a; }
$myfunctionNameStr = 'foo';
$myfunctionNameStr(2);
?>
Cause i don't think that you can dynamically construct a function declaration. You can decide at 'runtime' the value of the $myfunctionNameStr though.
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...
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();
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";
}
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";
}
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.
I'm sure there's a very easy explanation for this. What is the difference between this:
function barber($type){
echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
... and this (and what are the benefits?):
function barber($type){
echo "You wanted a $type haircut, no problem\n";
}
barber('mushroom');
barber('shave');
Always use the actual function name when you know it.
call_user_func is for calling functions whose name you don't know ahead of time but it is much less efficient since the program has to lookup the function at runtime.
Although you can call variable function names this way:
function printIt($str) { print($str); }
$funcname = 'printIt';
$funcname('Hello world!');
there are cases where you don't know how many arguments you're passing. Consider the following:
function someFunc() {
$args = func_get_args();
// do something
}
call_user_func_array('someFunc',array('one','two','three'));
It's also handy for calling static and object methods, respectively:
call_user_func(array('someClass','someFunc'),$arg);
call_user_func(array($myObj,'someFunc'),$arg);
the call_user_func option is there so you can do things like:
$dynamicFunctionName = "barber";
call_user_func($dynamicFunctionName, 'mushroom');
where the dynamicFunctionName string could be more exciting and generated at run-time. You shouldn't use call_user_func unless you have to, because it is slower.
With PHP 7 you can use the nicer variable-function syntax everywhere. It works with static/instance functions, and it can take an array of parameters. More info at https://trowski.com/2015/06/20/php-callable-paradox
$ret = $callable(...$params);
I imagine it is useful for calling a function that you don't know the name of in advance...
Something like:
switch($value):
{
case 7:
$func = 'run';
break;
default:
$func = 'stop';
break;
}
call_user_func($func, 'stuff');
There are no benefits to call it like that, the word user mean it is for multiple user, it is useful to create modification without editing in core engine.
it used by wordpress to call user function in plugins
<?php
/* main.php */
require("core.php");
require("my_plugin.php");
the_content(); // "Hello I live in Tasikmalaya"
...
<?php
/* core.php */
$listFunc = array();
$content = "Hello I live in ###";
function add_filter($fName, $funct)
{
global $listFunc;
$listFunc[$fName] = $funct;
}
function apply_filter($funct, $content)
{
global $listFunc;
foreach ($listFunc as $key => $value)
{
if ($key == $funct and is_callable($listFunc[$key]))
{
$content = call_user_func($listFunc[$key], $content);
}
}
echo $content;
}
function the_content()
{
global $content;
$content = apply_filter('the_content', $content);
echo $content;
}
....
<?php
/* my_plugin.php */
function changeMyLocation($content){
return str_replace('###', 'Tasikmalaya', $content);
}
add_filter('the_content', 'changeMyLocation');
in your first example you're using function name which is a string. it might come from outside or be determined on the fly. that is, you don't know what function will need to be run at the moment of the code creation.
When using namespaces, call_user_func() is the only way to run a function you don't know the name of beforehand, for example:
$function = '\Utilities\SearchTools::getCurrency';
call_user_func($function,'USA');
If all your functions were in the same namespace, then it wouldn't be such an issue, as you could use something like this:
$function = 'getCurrency';
$function('USA');
Edit:
Following #Jannis saying that I'm wrong I did a little more testing, and wasn't having much luck:
<?php
namespace Foo {
class Bar {
public static function getBar() {
return 'Bar';
}
}
echo "<h1>Bar: ".\Foo\Bar::getBar()."</h1>";
// outputs 'Bar: Bar'
$function = '\Foo\Bar::getBar';
echo "<h1>Bar: ".$function()."</h1>";
// outputs 'Fatal error: Call to undefined function \Foo\Bar::getBar()'
$function = '\Foo\Bar\getBar';
echo "<h1>Bar: ".$function()."</h1>";
// outputs 'Fatal error: Call to undefined function \foo\Bar\getBar()'
}
You can see the output results here: https://3v4l.org/iBERh it seems the second method works for PHP 7 onwards, but not PHP 5.6.