Introduction to Classes, Class Declaration and Objects


 

In last article we talked about PHP’s development history in context of Object Oriented Programming. The aim of this article is understand how PHP implements basic OOP concepts like Creating objects, Methods etc.

Classes and Objects

As you must already know classes define objects. A class is a group of items that share common attributes. Like a watch. An object is an instance of a class. For example, Rolex is an instance of watch class. In programming terms we can say “A Class is a code block that is used to generate objects”. If you are not familiar with basic concepts of Object Oriented Programming I’d recommend you to go through a few introductory articles on it. Here is the link to Wikipedia.

Creating Classes in PHP

Declaring classes is very easy. Each class declaration must begin with class keyword followed by class name. The code block of every class is enclosed within braces.

Class watch {
//Code for class
}

With the above code we have successfully declared a “type” of information. It certainly is of no use right now but this is how we start.

Creating Objects

As I said earlier, objects are instances or in more simple words an item of the category we refer to as class (Rolex can be categorized under Watches). Let’s us define that in code. Below is the how we define objects in PHP.

$rolex = new watch();

Yep. It’s that simple, like any other modern high level language. We use the new operator followed by the class name to generate an object. Now we have a $rolex object defined. But as the watch class itself is pretty un-useful, its instance rolex will reflect the same behavior.

We can define as many instances of a class as we like. Would you not like to have more watches? I would. Let us define one more.

$omega = new watch();

Even though nothing beats Rolex, it is always good to have options. ;)

PHP identifies each of these objects via its own unique identifiers. These identifiers only live as long as the object. To know what identifier an object has been assigned, you can use var_dump().

Var_dump($rolex);
Var_dump($omega);

Output:

object(watch)[1]

object(watch)[2]

The numbers in square bracket are respective identifiers.

Class Properties & Methods

By now you know how to define classes in PHP but do you really? The Watch class in its present form is of no use (and so is our rolex). Each class primarily has two features: properties and methods. Properties are the variables defined inside classes to hold data and Methods are special functions declared inside classes to perform tasks.

Properties

Properties vary from object to object. So, the value of price property of watch class will vary in rolex and omega objects.

Property declaration is similar to variable declaration except that each property must be preceded with its scope. A property can be public, protected or private.

We will discuss each scope in detail in later articles, let us first learn how to define these properties.

Class watch {
    Public $price = 0;
    Public $name = ”undefined watch”;
}

The above code defines three properties for watch class with default values. These properties can be accessed via object instances. To access these properties we use “->” character after the object name followed by the property name.

$rolex = new watch();
$rolex->name = “Rolex”;
$rolex->price = 8000;
$omega = new watch();
$omega->name = “Omega”;
$rolex->price = 6000;

All public properties can be assigned, read and updated directly. Hence each object can be identified with a unique name value.

PHP also allows us to dynamically declare object properties (i.e. we can use an arbitrary new property which hasn’t been defined in class structure and assign a value).

$rolex->model = “118238”;

But I would not recommend doing so; no developer would as this introduces a chance of producing inconsistent type/classes. For this reason this strategy is almost never used in practice.

Methods

A method declaration is similar to a function declaration except the function keyword must be preceded with its scope similar to property declaration.

Class watch {
    Public function getTime(){
        Return date(“m d Y”);
    }
}

It isn’t mandatory to always specify a scope before declaring a function. By default, each function is considered public if no scope is defined.

You can also pass arguments to the method like a normal function.

Class watch {
    Public function customTime($format){
        Return date($format);
    }
}

Calling an object’s method is similar to how we work with properties. We use the character “->” after the object name followed by method call. You must parenthesis like you would with normal function calls.

Echo $rolex->getTime();
$customFormat = “Y m d”;
Echo $rolex->getTime($customFormat);

Often we would want to work with an object’s properties. In such case, we use “this” keyword inside the method to refer to object’s properties.

class watch {

    public $name    = “undefined”;
    public price        = 0;

    Public function getNameAndPrice() {
        Return “{$this->name} is worth  {$this->price} dollars”;
    }

    Public function getTime(){
        Return date(“m d Y”);
    }

    Public function customTime($format){
        Return date($format);
    }

}

$rolex = new watch();
$rolex->name = “Rolex”;
$rolex->price = 8000;
Echo $rolex->getNameAndPrice();

Output:

Rolex is worth 8000 dollars

The $this is a pseudo-variable through which a class refers to its object instance.

A special method called the Constructor Method

Let us assume a situation where in we have a lot more properties to assign than just name and price, for example model number, serial number, discount etc. We can easily assign these many properties for a few watches but what if we have to create a catalogue of over a thousand watches? For lazy person like me it is a really big deal!

A simple way around this would be to pass all these values as arguments during object instantiation.

$rolex = new watch(‘Rolex’,’8000’,’model 11282’,’1x3452ct’,’20%’);

This would reduce the number of lines of code by a great deal. This is where the constructor method comes in.

A constructor method is invoked when we instantiate a class i.e. an object is created. This method can be used to perform tasks like setting essential properties, invoke other necessary methods and to do other important work. A constructor method is one of the magic functions of PHP and hence begins with two underscores.

class watch {

    public $name    = “undefined”;
    public price    = 0;
    public $model   = “undefined”;
    public serial   = “undefined”;
    public $discount = “0”;

    function __construct($name,$price,$model,$serial,$discount) {
        $this->name = $name;
        $this->price = $price;
        $this->model = $model;
        $this->serial = $serial;
        $this->discount = $discount;
    }

}

This method clearly reduces a lot of work. We can now create an object and pass on all the values straight away.

$rolex = new watch(‘Rolex’,’8000’,’model 11282’,’1x3452ct’,’20%’);
Echo $rolex->name;

Output:

Rolex

All the arguments supplied to the class are passed to its constructor function. This way we can ensure that an object is defined properly. It is recommended that you design your classes such that all its object are complete.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s