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 ...

Get Expert PHP and MySQL® now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.