Broad Network


PHP Compound Types

PHP Data Types with Security Considerations - Part 2

Foreword: In this part of the series, I give you the basics of PHP Object and Array Types. I also talk about some insecurities for array.

By: Chrysanthus Date Published: 16 Oct 2018

Introduction

This is part 2 of my series, PHP Data Types with Security Considerations. There are two compound types in PHP, which are the Object and the Array types. In this part of the series, I give you the basics of PHP Object and Array Types. I also talk about some insecurities for array. You should have read the previous part of the series before coming here, as this is the continuation.

The Object Type

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 part of the tutorial, I talk about a set of variables and functions. In one of the previous tutorials (volume), 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.

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 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 the 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 the 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 created (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.

Creating an Object from the Class
You create (instantiate) an object from the class 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 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.

I will say more about objects in a later part of the volume.

Is_type Functions

The is_object() Function
This function returns true if its argument is an object and false if it is not.

<?php

    class Calculator
        {
        }

    $var1 = $myObject = new Calculator();
    $var2 = 55;

    if (is_object($var1))
        echo 'it is object', '<br>';
    else
        echo 'it is not object', '<br>';
    if (is_object($var2))
        echo 'it is object', '<br>';
    else
        echo 'it is not object', '<br>';

?>

The output is:

    it is object
    it is not object

Insecurities of Objects
Insecurities from objects are more due to errors you, the programmer commits than from weaknesses of the PHP language.

Array
Imagine that you went to a party, and you met 7 new people. You can remember the names of 5 of them. For the remaining 2, you can remember or estimate their ages. You can remember the professions of the 7 people. You can put that information into an array as follows:

    $arr = array('John' => "accountant", 'Paul' => "teacher", 'Peter' => "doctor", 'Mary' => "lawyer", 'Susan' => "nurse", 35 => "businessman", 42 => "contractor");

A PHP array actually consists of key/value pairs. The keys are separated from the values by the arrow operator, => . Each element (key/value) is separated from the other by a comma.

In many cases, the key is a string and the value is a string. The key can also be an integer. If a key is 8, it is an integer. If the 8 is written in quotes, like '8', it is still an integer. However, '08' where 8 is preceded by zero, in quotes, is a string and not an integer.

Try the following code:

<?php

    $arr = array('John' => "accountant", 'Paul' => "teacher", 'Peter' => "doctor", 'Mary' => "lawyer", 'Susan' => "nurse", 35 => "businessman", 42 => "contractor");

    echo $arr['Paul'], '<br>';
    echo $arr[35], '<br>';

?>

The output is:

    teacher
    businessman

Is_type Functions

The is_array() Function
This function returns true if its argument is an array and false if it is not.

<?php

    $var1 = array();
    $var2 = 55;

    if (is_array($var1))
        echo 'it is array', '<br>';
    else
        echo 'it is not array', '<br>';
    if (is_array($var2))
        echo 'it is array', '<br>';
    else
        echo 'it is not array', '<br>';

?>

The output is:

    it is array
    it is not array

Insecurities with PHP Array
If you read a value with a key that does not exist, PHP does not stop with a fatal error. The array returns NULL. NULL is a valid value in PHP.

If you have a key as '08' and you use '8' to access the corresponding value, the array will return NULL, as '8' evaluates to an integer while '08' evaluates to a string. So, the key, 8 does not exist. Try the following code (the NULL value may not be printed):

<?php

    $arr = array('man' => "woman", '08' => "money");

    echo $arr['man'], '<br>';
    echo $arr[8], '<br>';

?>

There is more to PHP array and its insecurity. I will talk about that in a different series (in this volume).

Let us stop here, for this part of the series and continue in the next part.

Chrys


Related Links

Basics of PHP with Security Considerations
White 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

Cousins

BACK NEXT

Comments



Send the Writer a Message