Classes and Objects Basics in PHP
Classes and Objects in PHP - Part 1
Foreword: In this part of the series, I talk about Classes and Objects Basics, in PHP Object Oriented Programming.
By: Chrysanthus Date Published: 24 Nov 2018
Introduction
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, I talk about a set of variables and functions. In one of the previous tutorials, I talked about a set of statements that forms a function. Here, I am 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. In order to use the class, you have to create a particular unit from the class, everything being equal. That particular unit is called the object. In this part of the series, I give you the basic explanation of PHP classes and objects.
Group of Variables and Functions
Let us consider a group of variables and functions that would work as a generalized unit. Read and test 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 output.
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 that would receive the two new 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 task. An object is called the Instance of the 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 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 itself cannot solve a problem; that is, a class itself cannot carry out a task. It is an object created from the class that carries out a task; not the class.
When you create an object from a class, we say you are instantiating the object. Properties and methods of the class are called members of the class. An object created from a class has the same members 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;
}
}
$myObject = new Calculator();
$myObject->num1 = 2;
$myObject->num2 = 3;
$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 choose whatever name you want 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 even blocks inside the curly brackets. 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 (of the class) and the functions in the class are called methods. Both properties and methods are called members. In the creation of a basic class as the ones we are considering in this tutorial, you precede the statements in the class with the reserved word, public. The variables and the function we had in the previous code are the same variables and functions we now have in this class.
The reserved variable, $this refers to the object of the class. Note how it has been used to access the members of the class (object). In the class description, you use $this followed by -> and then the name of the member without any preceding $.
Read through the creation of the class above to appreciate how a class is defined (described).
Under normal circumstances, you define the properties (variables) in a class, and you do not initialize them (give them initial values). That is why in the above class, num1 and num2 do not have any values assigned to them. There is what is called constructor function, that can be used to assign initial values to them, when an object is created from the class (see below).
A class like the one above does not have a constructor function (see below). You create (instantiate) an object from it using the reserved word, new, such as in the line,
$myObject = new Calculator();
where $myObject is the name of your choice for an object, and Calculator() is like a function call to the class to create the object. This is done outside the class description (definition).
Using an Object
The aim of the class and object is to solve the problem, which the first code above solved. It is to add two numbers that are in two variables. You cannot use a class, you use but objects created from the class. Members of a class automatically become members of the instantiated object. You can create many objects from a class; the main thing you need is different variable names for the objects. To access a member of an object, you begin with the name of the object. This is followed by -> (minus sign then greater than sign), and then the name of the member without any preceding $. If the member is a method (function), you will have to follow the name with parentheses. These parentheses may have arguments, if the declaration or definition of the function had parameters.
To solve the above problem, we need to assign values to the properties (num1 and num2). This is what the second and third statements below the class description do. An object will not just solve your problem by itself. An object normally has one or more methods that you call to accomplish a particular task, using one or more properties of the object. The add method (function) of our object, does the addition using the two properties of the object; because of the way we defined the method. The fourth statement below the class description calls the add method and assigns the return value to a new variable, $result. The fifth statement displays the result.
The Constructor Function
If you want to create an object and at the same time initialize (assign values to) the properties, then you need what is known as the constructor function while typing the class. After this, to instantiate (create) an object from the class, you have to place the initial arguments in the class call. The following code illustrates this.
<?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(2,3);
$result = $myObject->add();
echo $result;
?>
Note how the constructor function has been defined using the reserved word, __construct and parameters. Outside (below) the class description the values were not assigned to the object again.
To have default values for the properties, just initialize the properties in the class. The following code illustrates this:
<?php
class Calculator
{
public $num1 = 2; #default value
public $num2 = 3; #default value
public function add()
{
$sum = $this->num1 + $this->num2;
return $sum;
}
}
$myObject = new Calculator();
$result = $myObject->add();
echo $result;
?>
The constructor (function) is not really needed here. Outside (below) the class description the values were not assigned to the object again.
Making Copies of Objects
To make a copy of an object, use the syntax:
$copy_of_object = clone $object;
where clone is a reservd word.
Read and test the following code:
<?php
class Cla
{
public $prop1 = 'first property';
public $prop2 = ', second property';
public function mthd()
{
echo $this->prop1 . $this->prop2 . '<br>';
}
}
$obj = new Cla();
$obj->mthd();
$objec = clone $obj;
$objec->mthd();
?>
$objec is now a copy of $obj . The output is:
first property, second property
first property, second property
There is more to Classes than I have given. However, I will not go into those extra bits in this basic tutorial. Let us stop here and continue in the next part, with more.
Chrys
Related Links
Basics of PHP with Security ConsiderationsWhite Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links