Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

PHP Development Part 5: Extending classes

Monday, April 16th, 2012 by Servage

This tutorial shows you how you can extend classes in PHP and thereby let child classes inherit functionality from parent classes.

On many programming paradigms the code is divided into defined parts for specific purposes. One of the most popular methods is the Model, View, Controller system (MVC), which is also used by most fameworks out there. In this example you will get a demonstration of how you could structure a model in PHP. Mainly it’s a class with certain standard functions you can use for all your classes.

class Model {

  var $data = array();

  function set($key, $value) {
    $this->data[$key] = $value;

  function get($key) {
    return $this->data[$key];


This gives you an idea of a general PHP model class. Obviously you could add any general functions here, which should be available in all the models you create based on this. For example methods for validating, saving and deleting data would be obvious addons here.

In your real models, the objects you actually use directly in your apps, you simply extend the parent object like so:

class User extends Model {

$user = new User;
$user->set('name', 'John Doe');
echo $user->get('name');

The variables and methods defined in the Model class are available in the User class, however, things defined in the User class are only available in the User class. This is really great to standardize functionality in parent classes and add special stuff to the individial child class. Hereby you reduce programming overhead and make it more effective to develop.

PHP Development Part 5: Extending classes, 4.7 out of 5 based on 3 ratings
Categories: Guides & Tutorials


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.