David Powers |
Tuesday, June 23, 2015
PHP’s gentle learning curve makes it an extremely popular choice for adding dynamic features to websites, such as sending email or retrieving content from a database.
Sure, it’s not the most perfect of languages—but neither is English. What makes them both relatively easy to learn is that you don’t have to wade through loads of theory before you can accomplish even the simplest of tasks.
But as you gain in confidence, PHP scripts become longer and longer, making them difficult to adapt to different projects. That’s when it’s time to bite the bullet and embrace PHP objects.
For me, the wake-up call came shortly after the first edition of my longest-selling book, PHP Solutions: Dynamic Web Design Made Easy, was published. Carolyn Wood, editor of the now-defunct Digital Web Magazine, picked it as her favorite book of 2006 because the code was easy to understand, and it solved common problems.
My elation was rapidly punctured by another review that criticized the use of “spaghetti code.” The reviewer was right: the code was project-specific, making it difficult to untangle and adapt for other projects. The second and third editions of PHP Solutions put that right by using objects where appropriate.
Technically speaking, an object is a data type capable of storing and manipulating values. It stores values as properties and has access to methods (functions) that perform various tasks. The properties and methods available to an object are defined by a class.
To the uninitiated, it all sounds very scary, but it’s not. PHP has a large number of built-in classes that make the transition from procedural code (step-by-step commands) to using objects painless.
What finally made sense of PHP objects to me was connecting to a MySQL database. PHP 5 introduced MySQL Improved (MySQLi) in two flavors: an object-oriented interface and procedural functions. In PHP 4, the code to submit a query was very simple. You passed the SQL and a database connection to a function like this:
$result = mysql_query($sql, $link);
The second argument was optional. If you left it out (most people did), PHP simply used the most recent connection. The equivalent procedural code for MySQLi looks deceptively similar:
$result = mysqli_query($link, $sql);
Not only is the name of the function slightly different (notice the i after mysql), but the order of the arguments is reversed, meaning that the database connection is no longer optional. At first, I thought this was just another example of PHP inconsistency in the order arguments need to be passed to a function. But that wasn’t the case. MySQLi procedural functions are simply aliases for creating objects. The functions were intended to make it easier to adapt existing code.
In MySQLi, the database connection is an object that controls interaction with the database. Consequently, it needs to be passed as an argument to MySQLi procedural functions every single time. This struck me as a waste of effort, so I decided to look into using the object-oriented interface. It was surprisingly simple. You start by creating your connection like this:
$link = new mysqli($host, $username, $password, $database);
The new keyword indicates that you want to create (instantiate) an object. That’s followed by the name of the class, in this case mysqli. The arguments between the parentheses are passed to the class constructor method to create the database connection. Apart from the new keyword, it’s exactly the same as using a function. The difference comes when you submit a query. $link now has access to all the MySQLi methods and properties through the arrow operator (a hyphen followed by a greater-than symbol). Submitting a query is simplified to this:
$result = $link->query($sql);
If the query is successful, $result is another object containing the result set. To find out how many rows it contains, you use its num_rows property like this:
$total_results = $result->num_rows;
The procedural equivalent looks like this:
$total_result = mysqli_num_rows($result);
If you’re still using PHP 4 functions to connect to MySQL, now’s the time to start updating your scripts. They’ll no longer work in PHP 7, which is scheduled to be released in November 2015. You can learn how to use MySQLi in my Accessing Databases with Object-Oriented PHP on lynda.com.
Once you get used to the idea of using the arrow operator instead of passing the object as an argument to a function, working with PHP objects becomes second nature. It also opens up a vast range of powerful tools in PHP. Most new features are being added as built-in classes. Among my favorites are the iterators in the Standard PHP Library (SPL) and the date- and time-related classes. Like MySQLi, these classes are built into the core of PHP, so there are no extra files to download or include into your scripts.
The real power of working with PHP classes and objects, however, is unleashed when you start creating classes of your own, or using third-party classes, such as SwiftMailer. Defining your own classes is no more difficult than writing a collection of custom functions because that’s what a class really is. It’s a collection of functions and variables designed to work together. The real value comes from creating code that’s easily reusable in different projects.
What distinguishes a well-designed class from procedural code is that each function performs only a single task and it’s not closely tied to a specific project. This often results in longer code. Converting one of the procedural scripts from the first edition of PHP Solutions to a class more than doubled the number of lines. But reusing the class in a completely different project required writing only six lines of code—a huge productivity win.
If I’ve whetted your appetite to learn more about creating your own PHP classes, check out Jon Peck’s course Object-Oriented Programming with PHP, and move your PHP skills to a higher level.
Tags: David Powers, PHP
Check out these popular Developer courses.
Thanks for signing up.
We’ll send you a confirmation email shortly.
Sign up and receive emails about lynda.com and our online training library:
Keep up with news, tips, and latest courses with emails from lynda.com.
We've updated our terms and conditions (now called terms of service).Go Review and accept our updated terms of service.