Archive for the ‘Magic Methods’ Category

PHP __call and __callStatic Magic methods

Sunday, August 24th, 2008

This is just a quick post to show the use of the magic methods __call and __callStatic. It’s following on in my Magic Method series. The concept is very similar to __set/__get, basically PHP attempts to call a method on a class, if it doesn’t exist the __call method is invoked (if it does exist). __callStatic is exactly the same but with static method calls.
Note that __callStatic will only be available from PHP 5.3 onwards.
Here is a quick example to show it in use;

<?php

// This example assumes ayou already have a DB connection

// established and a database has been [...]

PHP __set and __get Magic methods

Tuesday, July 29th, 2008

Object oriented programming principles encourage encapsulation, i.e. containing all the functionality inside a class. Usually this means member variables should be private or protected, one of the common ways to do this is with various set and get methods. In the case of a user class it may have setName, getName, setAge, getAge and so on. This can be time consuming to set up, change and maintain. The magic methods __set and __get provide a quick way to implement generic set and get methods.

<?php

 

class Foo{

   

    private $name;

    private $age;

   

    public function setName($name){

    [...]

Lazy Loading in PHP with __autoload

Saturday, April 26th, 2008

__autoload is one of the magic methods added to PHP in version 5. It creates a very easy way for you to manage all your different class files. Actually, with __autoload you don’t need to manage them.
Often you will see in PHP projects files that include the other files needed for that page. You can then end up with a while bunch of require_once calls and so on. This can be quite tedious to maintain and you may not always need all the files.
When you create a new instance of a class PHP checks for it and if it can’t [...]