Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save christophherr/52b27222b75af34a6549 to your computer and use it in GitHub Desktop.
Save christophherr/52b27222b75af34a6549 to your computer and use it in GitHub Desktop.
WordPress Developers Club Challenge - Object Buffering
//1.
//Hello World11.
//ob_flush sends the contents of the buffer.
//The first content is the echo "Hello World" and the second content is the string length (strlen) of "Hello World".
//Hello World echoes no matter what unless the buffer is "cleaned/destroyed" with ob_clean or ob_end_clean...
//2.
//Render out "Hello World"
//(I don't think I understood this correctly...)
<?php
ob_start();
echo "Hello World";
ob_flush();
?>
// Played around a bit and liked how this used the echoed value as variable outside of the buffer.
<?php
ob_start();
echo "Hello World";
$output_buffer = ob_get_contents();
ob_end_clean();
echo ( $output_buffer );
?>
//It was fun playing around with this.
// Thanky you for the brain teaser, Tonya!
@hellofromtonya
Copy link

Q1 - Perfect. Well done!

Q2: Yes that works. Here's other ways to do it too:

ob_start();
echo "Hello World";
ob_end_flush();

ob_end_flush() does the following:

  1. Sends out the output buffer (flushes it, which means it echoes it out)
  2. Turns off buffering.

If we needed to capture the contents to return, say in a filter for HTML (which I do all the time), then you can do:

function foo_filter( $output ) {
    ob_start();
    echo "Hello World";
    $output = ob_get_clean();
    ob_end_flush();

    return $output;
}

echo foo_filter( '' );

Excellent job!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment