Broad Network


OOP Basics in PHP

Object Oriented Programming in PHP – Part 1

Forward: In this part of the series, we look at PHP Object Oriented Programming basics.

By: Chrysanthus Date Published: 9 Aug 2012

Introduction

This is part 1 of my series, Object Oriented Programming in PHP. OOP stands for Object Oriented Programming. In this part of the series, we look at PHP OOP basics.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Prerequisite
There are other articles (tutorials) I have written in this blog on PHP. You need to have read them or similar articles, before reading this series. The titles of the articles in this blog, which are prerequisite to reading this series are:

- Getting started with PHP
- Variables as Synonyms in PHP
- Global and Function Variable Scope in PHP
- Some Scalar Data Types in PHP

A computer language builds up. There are certain things you have to learn first and then use them to learn higher things. Each of the above titles is either a tutorial or the first tutorial in a series. If it is the first part of a series, then you should have read the whole series. If it is a tutorial standing alone, then you should have read the tutorial. To reach any of the articles, just type the title of the article and my name Chrys in the Search Box of this page and click Search.

Preamble
When you have a set of variables and functions that work together and would appear in many parts of your code, you can put all that in one generalized unit, called a class. There will be no need for repeat typing of the set. In this tutorial, we are talking about a set of variables and functions. The set of variables and functions form a class, if brought together in a special way. The functions work with the values of the variables. Under that condition, it is possible that the values of the variables and the results of the accompanying functions can be changing. In order to use the class after it has been defined, you have to create a corresponding unit from the class, everything being equal. That particular unit is called an object. In this part of the series, I give you the basic explanation of PHP classes and their objects.

You should read this series in the order given; that is, you begin with part 1, then part 2, then part 3 and so on.

Group of Variables and Functions
Let us consider a group of variables and functions that would work as a generalized unit. Read and try the following code and note that it returns the sum of 2 and 3.

<?php

    $num1 = 2;
    $num2 = 3;

    function add($no1, $no2)
        {
            $sum = $no1 + $no2;
            return $sum;
        }

    $result = add($num1, $num2);

    echo $result;

?>

You have two variables (num1 and num2) and a function (add). In the code, the function is called, and the returned sum is held in the variable, result. The result is sent to the output (web browser).

Now the above code sums two particular numbers, which are 2 and 3. You would want a piece of code that sums any two numbers, not just 2 and 3. One possibility is to include another function that would receive the two numbers, change the values of the two variables, then call the add($no1, $no2) function. There is another possibility, which has become very popular over the years; it is to create a class, then create an object from the class that would add any two particular numbers.  A class is a generalized unit of code, from which things call objects can be created to do particular tasks. An object is called the Instance of a class. Note: in the above code the two variables ($num1 and $num2) and the function (add()), work together. That is why it is advisable to have the two variables and the function in one unit called a class.

Class
A class is a generalized unit (definition) from which objects can be instantiated (created). A class is basically a code unit that has variables and functions that work together. The variables are called properties and the functions are called methods. A class can solve a problem (carry out a task), but it is generally not advisable for a class to solve a problem. It is an object created from a class that is expected to carry out a task (solve a problem); not the class.

When you create an object from a class, we say you are instantiating the object. A variable of the class is called a property of the class. A function of the class is called a method of the class. Properties of a class are also called data members (of the class). An object created from a class has the same properties and methods as the class.

A Class and Object created from the above Code
The above code can be converted into a class and object as follows:

<?php

    class Calculator
        {
            public $num1;
            public $num2;
    
            public function add ()
                {
                    $sum = $this->num1 + $this->num2;
                    return $sum;
                }
        }

    $myObj = new Calculator();

    $myObj->num1 = 2;
    $myObj->num2 = 3;

    $result = $myObj->add();
    echo $result;

?>

You define a class beginning with the reserved word, class. Then you have a space and then follow it with the name of the class. You chose whatever name you want to give for the class. I have given the name Calculator because the class is doing some calculation. After the class name, you have a pair of curly brackets. There are statements and blocks inside the curly braces. All the statements for the class go inside the braces. It is conventional to type the variables first before the functions. The variables in the class are called properties and the functions in the class are called methods. In the definition of a basic class as the one above, you precede the properties and methods with the reserved word, public. The variables and the function we had in the previous program are the same variables and function we now have in the class.

Inside a method (function) definition in a class definition, to access a property, you begin with the predefined variable, $this. $this means the class or object that has the method. After typing $this, you type the arrow operator, ->. After that you type the name of the property (variable) without the $ sign. Read through the description of the class above to appreciate how a class is defined.

Under normal circumstances, you declare the properties in a class, and you do not initialize them. That is why in the above class, num1 and num2 do not have any values assigned to them. That is a common practice. You can still assign values to the properties if you want to, as you would do to variables outside the class. There is what is called constructor function that can be used to assign initial values to them as an object is being created (instantiated) from the class (see later).

Note: It is customary to begin the name of a class with a capital letter and the name of an object with a small letter.

Creating an Object from the Class without Constructor function
A class like the one above does not have a constructor function (see later). When a class does not have a constructor function, you instantiate an object from it, beginning with the reserved word, new. This is followed by a space and then the name of the class, followed by parentheses. The word, new is an operator, which returns a reference, to the object created (instantiated) on a region in memory. The returned reference is assigned to a variable. Note in the above program how the object, $myObj is instantiated.

Normally it is the object that carries out your task and not the class. You can however make the class to carry out your task but that is not a good practice. The instantiated object has all the properties and methods that the class it was instantiated from, has. The class and the instantiated object can be considered as two different pieces of code in memory. To access a property or a method of an instantiated object, you type the name of the object first, then the arrow operator and then the name of the property without the $ sign or the name of the method.

In the above program, the object $myObj is instantiated and then its property, num1 is given the value, 2 and its property num2 is given the value 3. You can instantiate a different object in the same way giving it a different name and different values for the same properties. Read through the above program thoroughly and try it.

Default Property Values
A class can have default property values. To achieve this, you just assign values to the properties as you define the class. Any object instantiated from that class will have the values automatically assigned to their properties. You can still change the values of the object properties, by just assigning new values. Well, giving default values to a class as I indicated previously is not a common practice. It is preferable to give values just after the class has been instantiated or during instantiation (see later).

Read and try the following program:

<?php

    class Cla
        {
            public $num1 = "man";
            public $num2 = "woman";
    
            public function display()
                {
                    echo $this->num1 . " and " . $this->num2;
                }
        }

    $obj = new Cla();

    $obj->display();

?>

Class Constants
Like default values, you can give constant values to properties of a class. Any object instantiated from that class will have the properties, constant. This is different from default values in the sense that the values of the properties in the class and instantiated objects cannot be changed. To achieve that you just precede the variable (property) in the class definition with the reserved word, const. Here, the variable, does not take the $ sign when it is declared and when it is used. Read and try the following program;

<?php

    class Cla
        {
            const pi = 3.14;
    
            public function display()
                {
                    echo self::pi . " as pi for this class and its instantiated objects cannot be changed.";
                }
        }

    $obj = new Cla();

    $obj->display();

?>

To access the constant property in a function in the class definition, you use, self, followed by the double colon operator (::).

Note: properties and methods of a class are called members of the class. Properties can be called data members and methods can be called member functions.

We have seen enough for this part of the series, let us stop here and continue in the next part.

Chrys

Related Links

Major in Website Design
Web Development Course
HTML Course
CSS Course
ECMAScript Course
PHP Course
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message