You are on page 1of 8

C odular

Home • Writers • RSS

Introducing PHP Classes
Introduction
Working with classes in PHP is a great way to
streamline your code, and make it awesome.
Classes or object oriented (OO) programming are
Artisanal tools, great
prices. Scrivener,
sometimes seen as behemoths of satan, but actually
Tinderbox,
DEVONthink, BBEdit, &
they're easy. Once you understand all the various
more. ads via Carbon
levels of privacy, extensions and more recently
magic methods. For the sake of simplification we'll be using PHP, and
modelling a man and a woman as classes, with a few basic attributes of
varying privacy levels.

Man + Woman = Person

Artisanal tools, great
prices. Scrivener,
Tinderbox,
DEVONthink, BBEdit, &
more. ads via Carbon

Men and women are pretty similar - a lot more similar than people think,
but there are some crucial differences. Some of the shared attributes are
things like eye colour, hair colour, height and weight. But there are a
couple of glaring differences between the two such as reproductive
organs, gender and chromosomes.
The way that inheritance works in classes is that you put as many
common items within one class and then extend that parent class for each
sub-class. Sound complicated? Let me clarify, we have a class of Person
that will be extended to create Man and Woman . There will be some specifics

public and private .Can be called from only within the current class or any children of that class (eg: gender can be altered by Person or Man ) Private . } } As you can see.Can only be called by the containing class. Protected . You can imagine this as the variables within Person being copied to a new class called Man so they are available to use if their privacy allows. outside of the class. we look to add a constructor. protected $genitalOrgan = ''. this means that when you create a new man using new Man() the constructor will run and we can set the gender specific attributes: class Person { private $alive = true true. To run an action on initialisation of a class. or even in a child.Can be called anywhere. } class Man extends Person { public function __construct __construct(){ $this->gender = 'male'. Privacy What you'll see in the above code is words such as protected . protected $gender = ''.that we set by default when we create a new Man or Woman . inside the class. (eg: alive can . these are varying levels of privacy and dictate where these attributes can be altered. $this->genitalOrgan = 'penis'. we have used the word extends to show that Man is an extension of the Person class. or functions called: Public .

I can call the parent method by using parent::method() . } } Site::relativeTime() /* If we had to instantiate the class we'd do $site = new Site. If I have overwritten a method within a child class. which has a helpful static function. Some things are clearer with examples: static class Site { public static function relativeTime relativeTime(){ return 'Yesterday'. parent. you'll see reference to $this . so I can access inherited variables using $this as above. relativeTime . $site->relativeTime(). For example if we had a class. */ When within a static function we can't use the $this notation. self. static Above. this just refers to the current instance of the object that you're in. as that refers to instantiated objects only. so for example if we had a constructor within the Person class we would call that from our Man class by using parent::__construct() methods of classes can cause some complications. this works very much the same as the parent keyword that is . we could call that function by using the code Site::relativeTime() . Site . $this can and does creep up the chain. A static method is one that you can call without having to instantiate an instance of the object that you're using. so we will want to use the keyword self .only be altered by Person ) $this.

$value){ echo 'Setting ' . $value. or try to call a function that doesn't exist. There are 4 that I'll run through.mentioned above. One thing to note is. $person->name = 'bob'.as with active record methodology variabes are stored within an array called data in the class: class Demo { private $data = array array(). } public function __get __get($variable){ if if(isset isset($this->data[$variable])){ return $this->data[$variable]. here we can gracefully handle that by actually using a method to handle that. this is the instance by where you can have a generic function that is called if you try to get or set a variable that doesn't exist. __set() . ' to ' . This is very useful if . if you're attempting to modify a static variable. and they're all very similar they are __get() . __call() and __callStatic() . Make sure that you declare all of these as public. }else else{ . public function __set __set($variable. $variable . Magic Methods Sometimes referred to as Overloading. Set and get If we try to set or get a variable that doesn't exist. inherently PHP will throw an error. // Set variable of instance of 'Person': $person = new Person(). $this->data[$variable] = $value. you will have to use a $ as well before the variable name see the differences below: // Set static variable 'name' of 'Person': Person::$name = 'bob'.

'). // Get what we just stored echo $d->test. 3)]. public function __call __call($name. and the other not. return $this. Overloading will not overload on a variable that already exists. our code before would use that variable instead of storing in the $data array.die die('Unknown variable. } } } $d = new Demo. it will call the overloading methods. Call and callStatic These two do the same thing. Also. 3)] = $arguments[0]. // Set a non-existent variable $d->test = 'Test Variable'.'). . // Get a non-existant variable echo $d->testFail. case 'set': $this->data[substr($name. 3)])){ return $this->data[substr($name. $arguments){ switch switch(substr($name. }else else{ die die('Unknown variable. } break break. ie: accessing a private variable outside the object. So for example if we had a variable defined called $test . 0. if you try to use a set or get on a variable that you don't have access to. 3)){ case 'get': if if(isset isset($this->data[substr($name. You can use these to call special functions that don't actually exist in the class. for example we could use a class to set or get instead of using the earlier methods: class Demo { private $data = array array(). except that one is for static methods.

it will create one.'). then return the instance: class DemoSingleton { private static $instance = NULL NULL. // Get a non-existant variable echo $d->gettestFail(). Singletons A singleton class is a class that should only be instantiated once and never instantiated again.break break. } } .this will check if and instance exists. public static function getInstance getInstance(){ if if(is_null(self self::$instance)){ self self::$instance = new self self(). // Get what we just stored echo $d->gettest(). One thing to note is that I have included the line return $this. } } } $d = new Demo. } return self self::$instance. This is normally achieved by having a static variable within the class sometimes named instance . and a static method called getInstance . if it doesn't. default default: die die('Unknown method. The logic is exactly the same for __callStatic() . // Set a non-existent variable $d->settest('Test Variable'). this will mean that you can chain your sets: $d->settest('test')->settest2('test2')>settest3('test3'). within the set case. for example if you had a class for database interfacing you would only want that instantiated once.

The best way to autoload a class is to use a global function called spl_autoload_register() .0+. such as the use of Factories and abstract functions . } spl_autoload_register('autoload_class').php'). So trying to instantiate a class called Person would look to include a file called Person. there are two ways to use it .php .$class = DemoSingleton::getInstance().class. '. // Using an anonymous function spl_autoload_register(function($class){ include_once include_once('includes/' . $class . These will both look in a directory called includes for a file with the same name of the class you're trying to instantiate. $class . The advantage of this is that only classes that you want to instantiate & use will be included in your page and will keep memory usage down.php') }).which I've only .class.3. Autoloading Autoloading is very nifty. Final Thoughts Object oriented programming is an amazing feature and is definitely something that you should use.class. OO can go so much further than what I have explained here. The other way is a named function. both below do the same thing: // Using a named function function autoload_class autoload_class($class){ include_once include_once('includes/' . whether exploiting extensions and magic methods or not. '. but this is only possible in PHP 5.my favourite is using an anonymous function.it allows you to load the file that a class is written in automatically when you try to instantiate it. and is used in a lot of large frameworks .

Tag: PHP Tweet Posted 14th July 2012 by Michael Top .ever had the need to use once. For further reading take a browse through the PHP Classes & Objects Manual.