Intro Object Oriented Programming

Published on Apr 16, 2011 by Pim Elshoff

Programming #OOP #Concept #Definition #PHP

I’m going to try and present the very shortest explanation of what OOP is. Even though the concepts we will be talking about are equally valid in most, if not all, modern programming languages that use OOP as their paradigm, I will use PHP in my examples because that’s the language I work with the most. So let’s dig in! 

Classes and objects

Image: Idea go / FreeDigitalPhotos.netOOP is a programming paradigm (a way in which you can tell the computer what to do) that allows you to:

  1. define structures consisting of sets of variables and sets of functions
  2. make variables that use these structures as blueprints and execute statements

These structures are called classes and the variables you make using classes are called objects. Making an object is called instantiation and an object is an instance of its class. Example of a class definition:

class Person
{
    public $name;
}

Example of some object definitions:

$pim = new Person();
$pim->name = “Pim”;
$you = new Person();
// Please e-mail your name so I can fix my program
$you->name = “unknown”;

So in short: classes are blue prints; objects are created from those blue prints. That’s all!

Properties and methods

Ok I lied, that’s not all. When a class defines a variable, it is called a property. When a class has a function, it’s called a method. As you may have seen before, in PHP the properties of an object (not class; remember that the class is only the definition, the object is the real deal!) are accessed with the -> operator. Methods of a class are accessed in exactly the same way:

class Person
{
    public $name;

    public function echoName()
    {
        echo “My name is $this->name”;
    }
}

$pim = new Person();
$pim->name = “Pim”;
// prints: My name is Pim
$pim->echoName();
$you = new Person();
$you->name = “unknown”;
// prints: My name is unknown
$you->echoName();

So what’s up with the public stuff? And the $this thingy?

The $this variable means: take the object that the function we are in was called for, and use that to access whatever comes after the -> operator. That’s why the $pim object displays “My name is Pim”; because that object has value “Pim” for property $name, whereas object $you has value “unknown” for property $name.

Access and encapsulation

Imagine I did this:

$pim = new Person();
$you = new Person();
$pim->name = $you;
$you->name = $pim;

Now that’s just freaky. I don’t think it’s ok for names to not be a string. I think I want to make sure that my class Person’s property $name can only have values of type string.

class Person
{
    private $name;

    public function setName($newName)
    {
        if (is_string($newName)
        {
            $this->name = $newName;
        }
    }
    ...
}

$pim = new Person();
$pim->setName(“Pim”);
// My name is Pim
$pim->echoName();
$pim->setName(123);
// My name is Pim; 123 is not a string!
$pim->echoName();
$you = new Person();
$pim->setName($you);
// My name is Pim; $you is not a string!
$pim->echoName();
// The program crashes: name is private
$pim->name = $you;
// The program never reaches this point
$pim->echoName();

By setting $name to private we tell the computer that $this->name is the only way to access $name. There are three access levels: public, protected and private. Public means that the property or method is always accessible. Private means only the object itself can access the property. We’ll get to protected later.

One of the most important ideas of OOP is called encapsulation. Encapsulation means: hiding how something works on the inside and only showing how you can use it on the outside. Why is this important? Say we want to make a ‘Square’ class. Would you store the center point and the distance to the edge? Or store one corner and the width? Would you store as much as you can? None of that matters when the programmer who will use your class calls ‘$square->drawYourselfOnTheScreen()’. The programmer that will continue your hard work on class ‘Square’ may change the whole thing around on the inside, but on the outside ‘drawYourselfOnTheScreen()’ must still work, even if the inner workings are different.

With encapsulation your class becomes a small program in and of itself. It has input and output, but no one needs to peek inside how it achieves all that. With OOP and encapsulation, programming becomes less like cooking (do x, now do y, now do z) and more like lego (block x on top of block y next to block z)!

The constructor

In every class you can define a special method that will be called when you create a new object. This method is called the constructor. In many program languages the constructor is named after the class, but in PHP the constructor is named __construct().

The constructor method can take parameters like any regular method. See this example for how passing arguments to the constructor works:

class Person
{
    private $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
    ...
}

$pim = new Person(“Pim”);
$you = new Person(“unknown”);
// My name is Pim
$pim->echoName();
// My name is unknown
$you->echoName();

Similarly to the constructor, many languages offer a method called a destructor. This method will be called just before the object will be cleared from memory. In PHP this method is named __destruct().

PHP5’s magic methods

PHP has more methods that allow for some behavior that may seem a bit magical. These methods are aptly named ‘magic methods’. See the PHP manual for a list of methods and what they do.

Others

There are a few other noteworthy concepts in OOP.

Static methods and properties are not called on an object, but on a class. This means that all instances that use a static property use the same one. This is fundamentally different from normal properties; every object has its own. Static methods and properties are subject  to the public, protected and private access keywords.

This also means that you cannot use the $this keyword in the body of a static method. In PHP you càn call a static method non-statically, but it shouldn’t be allowed. Ever.

Constants are similar to static properties, but a constant has to be instantiated in the declaration and cannot be altered during run-time. They are just like regular PHP defines, except that they are bound to a class.

To access a static property or method or a constant you don’t use the object variable name, but the classname. You also don’t use the object access operator (->), but the scope resolution operator(::).

Here are some examples. These are bad coding practices and are meant to illustrate the concepts only!

class Person
{
    // No person’s name is ever longer than 3 characters
    const PERSON_NAME_LIMIT = 3;
    // Keep track of the total amount of persons in the system
    private static $totalPersonCount;
    ...
    public function __construct($name)
    {
        if (strlen($name)         { ... }
        self::$total++;
    }

    public static function getTotalPersonCount()
    {
        return self::$total;
    }
}

echo Person::getTotalPersonCount();   // 0
$pim = new Person(“Pim”);
echo Person::PERSON_NAME_LIMIT;       // 3
echo Person::getTotalPersonCount();   // 1
echo $pim->PERSON_NAME_LIMIT;         // Error!
echo $pim::getTotalPersonCount();     // Very error!
// This will actually work, silly PHP
echo $pim->getTotalPersonCount();

Concluding

With all these concepts in mind you are well on the way of grasping OOP, but there is still a lot more ground to cover. Because I’m such a fan of definitions and because I believe that a proper grasp of definitions makes communication a lot easier, here is a list:

  • A class is a definition of a type, consisting of a set of variables, a set of functions and a set of constants.
  • A variable in a class is called a property.
  • A function in a class is called a method.
  • An object is a variable that is instantiated from a class.
  • An accessor is a keyword that defines from which scope the describes property or method may be accessed. There are 3 access levels:
    • Public properties and methods can be called from outside the object.
    • Protected properties and methods can be called from inside the object and up the class hierarchy.
    • Private properties and methods can be called from inside the object alone.
    • Encapsulation is the concept of hiding the inner workings of a class and providing public methods to interact with the class.
    • The constructor is the method of a class that is called when a new object is instantiated.

This article is part of the Object Oriented Programming series.

  1. Intro Object Oriented Programming
  2. Inheritance
  3. Polymorphism
  4. SOLID design
Pim Elshoff

About the author

Pim has been working the web since 2004! Read more about Pim

Comment(s)

Be the first to comment!

Trackbacks

No trackbacks yet

Leave a comment

All comments will be moderated

  Veld is verplicht
Captcha
  I'm terribly sorry that this is necessary and I appreciate the effort you are taking to post a comment!