Sunstorm Labs Blog

March 14, 2008

register_shutdown_function after all the other register_shutdown_functions

Filed under: PHP — Tags: — admin @ 4:35 pm

PHP’s register_shutdown_function lets me run code after it finishes running the script, be that naturally or forcibly. This makes it a perfect fit for a whole bunch of things, like running maintenance database queries or showing debugging information.

function do_maintenance()
{
  $db->doSomeQueries();
}
 
function debug_write()
{
  echo 'some debugging information';
}
 
// Last things to execute
register_shutdown_function( 'do_maintenance' );
register_shutdown_function( 'debug_write' );

There’s one caveat, and it’s explained in the PHP documentation:

Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered.

(more…)

February 29, 2008

What good are ArrayObjects?

Filed under: PHP — Tags: , — admin @ 8:00 am

Ever since I had my first encounter with the SPL, it took me a while to understand the actual usefulness of the ArrayObject. Its use isn’t obvious, because it only reveals itself if you want to follow a strict discipline of class encapsulation. Otherwise it doesn’t offer any advantage over the standard PHP array.

A lot of the confusion comes from the lack of documentation. An ArrayObject, the documentation says, is “an array wrapper”, that “allows to recursively iterate over Arrays and public Object properties”. This isn’t very useful, and it doesn’t explain at all what is the ArrayObject actually good for. Iteration over arrays and objects has been long supported simply with the foreach construct:

$arr = array( 'a', 'b', 'c' );
$arr[0] = 'A';
$arr[] = 'd';
 
echo count( $arr );
 
foreach( $arr as $letter )
  echo $letter;

And this is how you’d do it with an ArrayObject:

$arrObject = new ArrayObject( array( 'a', 'b', 'c' ) );
$arrObject[0] = 'A';
$arrObject[] = 'd';
 
echo count( $arrObject );
 
foreach( $arrObject as $letter )
  echo $letter;

(more…)

Powered by WordPress