Re: Re: Throwing an exception seems to defeat output buffering

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



2009/2/3 Shawn McKenzie <nospam@xxxxxxxxxxxxx>

> Wickland, Leif wrote:
> > I would expect that if I turn on output buffering, echo something, throw
> an exception, and catch the exception, nothing will have been actually
> output..  That doesn't seem to be the case.  Throwing an exception seems to
> defeat output buffering.
> >
> > In the following code, I would not expect to see the <h1>, but I do.
> >
> >
> >
> > <?
> > try {
> >     ob_start();
> >     echo '<h1>You should not see this!</h1>';
> >     throw new Exception('<h2>This should be the first output.</h2>');
> >     exit( 'Contents: ' . ob_get_clean());
> > }
> > catch (Exception $ex) {
> >     exit('<h2>Exception:</h2>' . $ex->getMessage());
> > }
> >
> >
> >
> >
> > I'm exercising that code on PHP 5.2.4 and 5.2.8.
> >
> > Does anybody know why throwing an exception seems to override ob_start(),
> flushing the buffered output?
> >
> > Thank you,
> >
> > Leif Wickland
>
> Others have told you why, so these will work as you want (depending upon
> what you want :)  You can use ob_end_clean() unless you need the
> contents of the buffer.  I assigned the return of ob_get_contents() to a
> var because I assume you have the exits() for testing.
>
> <?
> try {
>    ob_start();
>    echo '<h1>You should not see this!</h1>';
>     $buffer = ob_get_clean();
>     throw new Exception('<h2>This should be the first output.</h2>');
> }
> catch (Exception $ex) {
>    exit('<h2>Exception:</h2>' . $ex->getMessage());
> }
>
>
> -- or --
>
>
> <?
> try {
>    ob_start();
>    echo '<h1>You should not see this!</h1>';
>    throw new Exception('<h2>This should be the first output.</h2>');
> }
> catch (Exception $ex) {
>    $buffer = ob_get_clean();
>     exit('<h2>Exception:</h2>' . $ex->getMessage());
> }
>
>    Or you can create a custom exception class, and add the above
functionality in the constructor. Either clean the buffer, or save it within
the exception of needed. That way you won't have to bother with ob, if you
use this often.

>
> --
> Thanks!
> -Shawn
> http://www.spidean.com
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


-- 
Alpar Torok

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux