PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

9 Magic Methods in PHP

Note: This article was originally published at Planet PHP on 11 December 2012.
Planet PHP

This post forms part of a series of articles about using PHP to do objected oriented programming, or OOP. They were originally published elsewhere but are no longer available at that location, so I'm reposting them here. Previously in the series was an introduction to OOP in PHP, in two parts

The title is a bit of a red herring as PHP has more than 9 magic methods, but these will get you off to a good start using PHP's magic methods. It might be magic, but no wands are required!

The "magic" methods are ones with special names, starting with two underscores, which denote methods which will be triggered in response to particular PHP events. That might sound slightly automagical but actually it's pretty straightforward, we already saw an example of this in the last post, where we used a constructor - so we'll use this as our first example.

__construct

The constructor is a magic method that gets called when the object is instantiated. It is usually the first thing in the class declaration but it does not need to be, it a method like any other and can be declared anywhere in the class. Constructors also inherit like any other method. So if we consider our previous inheritance example from the Introduction to OOP, we could add a constructor to the Animal class like this:

class Animal{ A public function __construct() { $this-created = time(); $this-logfile_handle = fopen('/tmp/log.txt', 'w'); } A }

Now we can create a class which inherits from the Animal class - a Penguin! Without adding anything into the Penguin class, we can declare it and have it inherit from Animal, like this:

class Penguin extends Animal { A } A $tux = new Penguin; echo $tux-created;

If we define a __construct method in the Penguin class, then Penguin objects will run that instead when they are instantiated. Since there isn't one, PHP looks to the parent class definition for information and uses that. So we can override, or not, in our new class - very handy.

__destruct

Did you spot the file handle that was also part of the constructor? We don't really want to leave things like that lying around when we finish using an object and so the __destruct method does the opposite of the constructor. It gets run when the object is destroyed, either expressly by us or when we're not using it any more and PHP cleans it up for us. For the Animal, our __destruct method might look something like this:

"/

Truncated by Planet PHP, read more at the original (another 23894 bytes)