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?

0


source to share


6 answers


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';

      

+6


source


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?

+2


source


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 );

      

+1


source


Functions are supposed to return data and then your application processes it the way you want, whether it assigns it to a variable or echo.

+1


source


It's good. I'd rather see PHP blend completely with HTML.

You can use this instead <?= my_function() ?>

if you want to write a little less code.

0


source


What @DaveRandom said in his comment. Also, no, this isn't necessarily bad practice. It can, though, do for code that is difficult to debug. Instead, consider an MVC approach, where the logic is mostly in the controller and the view just handles rendering based on that logic.

0


source







All Articles