Is it bad practice to echo function in php?
Not bad practice to respond to a bunch of HTML with a function in php and have something like this:
function my_function() {
global $post;
$custom_fields = get_post_custom();
$some_field = $custom_fields ['some_field'][0];
?>
<div class="something <?php if ($some_field) { echo $special-clas;} ?>">
<div class="something-else">
/* bunch more of html code */
</div>
</div>
}
And then on the page, where do you want to echo it?
<html>
<body>
.....
....
<?php echo my_function(); ?>
....
I'm not sure how is it "customary" to do echo functions?
source to share
Consider two functions:
function does_return() {
return 'foo';
}
function does_echo() {
echo 'bar';
}
does_return(); // nothing displayed
echo does_return(); // 'foo' displayed
does_echo(); // 'bar' displayed
echo does_echo(); // 'bar' displayed
In both cases, CAN pin can be executed, but the way it is is different. Since it does_return()
does not itself have ANY code to execute the output within its definition, the output depends on the calling code, for example. echo
you are doing.
C does_echo()
, it doesn't matter how you call the function (with or without echo), since the function does the output itself. you get bar
whatever.
Now consider the following:
function this_is_fun();
echo 'foo';
return 'bar';
}
this_is_fun(); // outputs 'foo'
echo this_is_fun(); // outputs 'foobar';
source to share
This is bad practice because it makes your code harder to work with.
With this feature, you mix logic and presentation. So, when you see something on your output that you don't like, you cannot be sure where to go first to go and change it. Are you going to page code or function code?
source to share
I don't see how bad it is. As long as you reuse the function, it seems that you are using it correctly.
The only thing you don't need to do is use global
; rather pass $post
functions. See this answer for what.
Since your function already has an output, you don't need it echo
.
my_function( $post );
source to share