Create Callbacks Using __invoke
The __invoke magic method (available as of PHP 5.3) is used to make an object callable as if it were a regular function. The combines the usefulness of objects with the simplicity of functions. One application of this feature is creating callback functions that can be passed around like objects. This is common practice in other languages like JavaScript, and can be very useful. This tutorial will show you how to create a callback function using the __invoke method.
Deciphering Magic Methods in PHP
Deciphering Magic Methods in PHP | Nettuts+
PHP provides a number of ‘magic’ methods that allow you to do some pretty neat tricks in object oriented programming. These methods, identified by a two underscore prefix (__), function as interceptors that are automatically called when certain conditions are met. Magic methods provide some extremely useful functionality, and this tutorial will demonstrate each method’s use.
Read full tutorial at Nettuts+
Snippet: Maintain a Single Database Object in PHP 5 Using the Singleton Pattern
When creating a PHP application, it is usually necessary to connect to a database to perform certain tasks. In some cases you only want to open a connection when necessary, but limit it to a single connection. This way you don't waste resources on unnecessary database connections. For these situations I use the Singleton Pattern, which is perfect for this.
In this example, we are creating a MySQLi object and forcing it to a single instance. We just need to call DB::get() to create and/or access the object.
What’s new in PHP 5.3?
With last week's announcement of RC4, the final release of PHP 5.3 is imminent. So what can we expect in this version? Here I'll outline the biggest and most interesting changes and additions. This is definitely not exhaustive since there are tons of minor changes and improvements in this version, but these are some of the ones I found interesting.
Snippet: Autoloading Objects (PHP 5)
When writing the PHP that powers TempServers, I wrote the core functions into classes for better organization and efficiency. To make things further organized, each class is stored in individual source files, no matter how small. The problem here is keeping track of which classes are used where, in order to include the appropriate source files. Fortunately, PHP 5 offers a solution: autoloading.
This comes in the form of the __autoload function which automatically gets called if a class is called that does not exist. Here's what it looks like:
function __autoload($class) { require_once(strtolower($class) . '.class.php'); }
Usage
- Place each PHP class in individual files named after the class followed by .class.php (Example: class MyClass goes in a file named myclass.class.php).
- Include the code snipped above into any file that might use one of your classes.
For more details, check out the PHP manual: http://www.php.net/manual/language.oop5.autoload.php
