O'Reilly logo

Expert PHP and MySQL® by Patrick Galbraith, Ronald Bradford, Andrew Curioso

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 2. Advanced PHP Concepts

WHAT'S IN THIS CHAPTER?

  • Using iterators

  • Making classes behave like arrays

  • Understanding Lambda-style functions

  • Using True lambda functions and closures

This chapter covers several concepts that can lead to better coding practices and cleaner, more manageable code. They are used in various chapters throughout the rest of the book and several of the concepts take advantage of the built-in functionality of the Standard PHP Library (SPL). Specifically, the four interfaces provided by the SPL allow programmers to easily utilize PHP's ability to iterate through data and create a data structure that behaves exactly like a PHP array.

This chapter also uses standard language constructs available in PHP 5.3.0 called lambda functions. Lambda functions are useful when they are used as closures to create dynamic functionality.

A fictitious book club database is used as the example for this chapter. The application is simple; it provides the minimal functionality and keeps the least amount of information about the books possible. This chapter goes over simple use cases.

A PROBLEM THAT NEEDS SOLVING

Loops are used in a typical PHP application to iterate directly through result sets fetched from MySQL:

<?php
$conn = mysql_connect( 'localhost', 'mysql_user',
                       'mysql_password', 'database' );
$result = mysql_query('SELECT * FROM 'example_table'', $conn);
if ( $result )
  while ( $row = mysql_fetch_assoc($result) ) {
    // Execute logic or display row
}
?>

The highlighted approach is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required