Broad Network


PHP Object Basics

Basics of PHP – Part 13

Forward: In this part of the series, I give you the basic explanation of PHP classes and objects.

By: Chrysanthus Date Published: 28 Jul 2012

Introduction

This is part 13 of my series, Basics of PHP. 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. Here we are talking about a set of variables and functions. At first we talked about a set of statements that forms a function. Here, we are talking about a set of variables and functions that form a class. 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. So in order to use the class, you have to create a particular unit from the class. That particular unit is called an object. In this part of the series, I give you the basic explanation of PHP classes and objects.

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.

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 and a function. In the code, the function is called, and the returned sum is held in the variable, $result. The result is then echoed to the browser.

Now the above code sums just two 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 the would receive the two numbers and then 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 task. An object is called the Instance of a class.

Class
A class is a generalized unit from which objects can be instantiated (created). A class is basically a code unit that has variables and functions that work together. In PHP the variables are called members and the functions are called methods. A class itself cannot solve a problem; that is, a class itself cannot carry out a task. It is an object created from a class that carries out a task; not the class. There are two ways of creating an object. You can create an object and be feeding it with different arguments so that it would be giving different results as it performs similar tasks. Alternatively, you can create different objects from a class and each would be giving a particular result as it performs a task that is similar to the tasks performed by other objects created from the same class. The members and methods of a class become the members and methods of an object created from the class. A class is meant to carry out similar tasks through its objects. The objects would give different results.

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 = 2;
                public $num2 = 3;

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

        $myObject = new Calculator();
        $result = $myObject->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 braces. All the statements of the class definition go inside the curly braces. It is conventional to type the variables first before the functions. The variables in the class are called members (of the class) and the functions in the class are called methods. In the definition of a basic class as the one we are considering in this article, you precede each declaration of a variable with the reserved word, public; you also precede the definition of each function with the same reserved word, public. The variables and the function we had in the previous code are the same variables and functions we now have in the class definition.

The $this variable is a reserved variable. It refers to the class or corresponding object concerned. See the use of the -> sign below.

Creating an Object from the Class
In the last code segment above, the first line we have is:

        $myObject = new Calculator();

You create an object from a class beginning with the reserved word, new; then a space and then the class name followed by parentheses. This expression returns the object. You assign the object to a variable, whose name you choose. I chose $myObject. You cannot see the object; the object exits somewhere in the computer’s memory. All members and methods of the class, automatically becomes members and methods of the object.

So define a class; after defining the class, you create an instance of the class as an object. The class itself does not carry out a task; it is the object, having the members and methods of the class that carry out a task.

To execute (call) a method you need the arrow (->), which is the minus sign followed by the greater than sign. To call a method, you begin with the name of the object. This is followed by the arrow, then the name of the method with parentheses. This expression may or may not return a value. If the method definition has a return statement, then the expression would return a value; if the method definition does not have a return statement, then the expression would not return a value. The return value of the expression can be assigned to a variable, whose name you choose. In the last-but-one statement in the code above, the return value of the expression is assigned to a variable. The last statement on the code sends the return value to the browser.

The problem with the above class is that its object can only add the numbers, 2 and 3. That is not really while you should have a class. A class should be able to have instantiated an object that would produce different results, such as given the sums of different pairs of numbers or a class should be able to have instantiated different objects where each would produce a particular result. In the above case, only one object can be instantiated from the class to produce only one result (the sum of 2 and 3).

In the following section we modify the class in such a way that it can be producing the sum of any pairs of numbers.

Object fed with different Arguments
Here we look at an object that would produce different results when fed with different arguments. The following code is a modification of the previous code.

    <?php

        $num1 = 2;
        $num2 = 3;
        
        class Calculator
            {
                public function add ($no1, $no2)
                    {
                        $sum = $no1 + $no2;
                        return $sum;
                    }
            }

        $myObject = new Calculator();

        $result = $myObject->add($num1, $num2);
        echo $result;

    ?>

The variables are still almost the way they were, but this time, they are outside the class definition. They are not part of the class or object. In the code you have a class definition. The class is still called, Calculator. The class definition begins with the reserved word, class, followed by the name of the class. A typical class would have variables and functions. The variables are called members and the functions are called methods. Here, we have just one function.

The function, now called method, receives two arguments and returns the sum of the two arguments (numbers). Everything in any class definition is enclosed in curly braces.

In the last code segment, the first statement instantiates an object from the class. Creating an object means instantiating an object from a class. An object is an instance of a class. This statement instantiates an object from the class. Remember, it is the object that would actually carry out a task, not the class. The object instantiated from the class is assigned to a variable.

The members and methods defined in the class automatically become the members and methods of the object created from the class. Here, there is only one method, no member, for the class and corresponding object.

The last-but-one statement calls the method passing two arguments, which are the variables declared outside the class. The last statement of the code sends the returned value to the browser.  

By changing the values of the two variables in the code, you would be having different results (sums). So the class we have here is better than the one we had before.

Objects with Particular Results
You can have a class whose instances will each produce a particular result. To facilitate this you use what is called a constructor method (function). The constructor method is like a predefined method, but comes without any statement. You are the one to put the statements. The statements for this method are usually used to initialize members (variables) for the class and its corresponding objects. The syntax for the constructor method is:

    void __construct ([ mixed $args [, $... ]] )

void means the method returns nothing. The square brackets and its content in the parentheses mean that the method can have no parameter (no argument), or can have any number of parameters separated by commas. mixed means the parameters and corresponding arguments can be of any type. __construct is a reserved word; it begins with two underscores immediately followed by “construct”.

In the following example, when an object is instantiated, it will only be possible for it to give the sum (result) of only two numbers. In other words, each object created would produce the sum of a specific pair of numbers. This is achieved thanks to the constructor method in the class definition.

The aim of this class is to solve the same problem that was handled above, but in a different way. In the class, there are two members (variables) that are not initialized (are not given values). When an object is created, the constructor method gives these members values; that is, the constructor method initializes them.

Note that in creating an object the class name has parentheses. The values to be used by the constructor method are passed as arguments in these parentheses. There is a difference between passing arguments with the parentheses of the class name and passing them with the parentheses of a method name. Those for the class name are to be used by the constructor method only. Those for the method name are to be used by the object in general terms.

The code for the example is given below. Read and try it.

    <?php

        class Calculator
            {
                public $num1;
                public $num2;

                function __construct($no1, $no2)
                    {
                        $this->num1 = $no1;
                        $this->num2 = $no2;
                    }

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

        $myObject = new Calculator(4,5);
        $result = $myObject->add();
        echo $result;

    ?>

Note that when you use $this followed by the arrow and a variable name, the variable name should not have the preceding $. Also note that you do not have to precede the constructor function with the reserved word, public.

The object in the code is created with the arguments 4 and 5. By changing these values as you create the object, each object created will give its own sum (result). With this code you do not need to pass the arguments through the add() method. So any object created gives its own result. In the previous code, you can have the one created object and be changing the arguments of the method call. The code, here, clearly shows how objects are instances of a class.

Inheritance
You can define a child class and create a corresponding child object from a class. This child class inherits all the members and methods of the class. The chain can continue downward ending up with grand children and great grand children. Each child inherits the members and methods of its parent. A child class can also be defined to have modified members and methods of its parents. That is, the value assigned to a member of the parent would be different for the child, but the member name would be the same; also the definition of a method for the parent would be different from that of the child, but still have the same name. This modification of members and methods for the child class is optional. A child normally has the same members and methods of the parent unless you modify one or more of them. The constructor method is also inherited. A child can have additional members and methods.

We continue with code of adding two numbers. In the following program, we have a child class of the class to add two numbers. This child inherits all the members and methods of the parent by default, and they are not modified. The child has one additional method, which is to determine and return the square of the sum (of the two numbers). You create a child class in a similar way that you create a class (parent). The only difference is that you begin the definition with the following syntax:

    class childName extends ParentName

The extends, reserved word is used. In the syntax, you have the name of the child and the name of the parent. The program mentioned is as follows:

    <?php

        class Calculator
            {
                public $num1;
                public $num2;
                public  $sum;

                function __construct($no1, $no2)
                    {
                        $this->num1 = $no1;
                        $this->num2 = $no2;
                    }

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

            }

        class MyChild extends Calculator
            {
                public function square ()
                    {
                        $this->add ();  //you have to add the numbers first before you square the sum.
                        $sqrValue = $this->sum * $this->sum;
                        return $sqrValue;
                    }
            }

        $myChildObject = new MyChild(6,7);
        $resultC = $myChildObject->square();
        echo $resultC;

    ?>

Read through the code and try it. The inheritance of the members and methods is done in the memory; you do not see it in the child code. You are the one to give the name for the child class; I gave the name, MyChild.

In the next program, the inherited object modifies the members and the definition of the method. In the modified method, a literal number is added

    <?php

        class Calculator
            {
                public $num1 = 2;
                public $num2 = 3;

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

        class MyChild extends Calculator
            {
                public $num1 = 4;
                public $num2 = 5;

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

        $myChildObject = new MyChild();
        $resultC = $myChildObject->add();
        echo $resultC;

    ?>

To modify members and methods, in the child class, you use the same declarations for the members and methods, but you change the values for the members and the definitions for the methods. Read and try the above code.

Accessing and modifying Members outside the Class
Let us see how you can read the values of members of a class or change them, outside the class. It is simple. To access the value of a member of a class, type the name of the created object. This should be followed by the arrow, (->); then the name of the member, without the $ sign. To change the value, assign the new value to this expression. The following code illustrates this. Read and try it.

    <?php

        class Calculator
            {
                public $num1 = 2;
                public $num2 = 3;

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

        $myObject = new Calculator();
        echo $myObject->num1; echo "<br />";

     $myObject->num1 = 50;
     echo $myObject->num1;

    ?>

The Arrow
As we have seen, the arrow is used to access a member or method for an object or class. When using the arrow, you do not precede the member with the $ sign.

I have given you the basics of PHP Classes (and objects). I have used very simple examples. If you have a task in a project, you will at that time determine what feature you have learned here, that you would use for the task. You can also combine the class and object features, learned in this article, in solving a problem.

Before we leave this part, there is something you should appreciate: The use of the, $this, reserved variable, prevents you from using the reserved word, global, in a class.

We have done a lot, let us stop here and carry on in the next part of the series.

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