IMG 20211026 210759 217 Introduction To Classes and Objects In PHP

Introduction To Classes and Objects In PHP 7

What is a class?


In object oriented programming, a class is a blueprint of an object.

This definition doesn’t tell us much about what exactly a class is, because you are probably going to ask next, "What is an object?" Well, that is the nature of object oriented programming: classes and objects are defined in terms of each other. Let us leave the definition of an object for later.

To make it easy, let me use an analogy. Let us say we want to build a house.

  • First we draw the plan or the blueprint of the house, showing what the house will be like.
  • Next we build the house according to the blueprints.
  • If someone wants to be the same house, we can give them the same blueprints to build their house too.

Now, back to our object oriented world, the blueprint represents the class and the house represents the object. We can instantiate an object from a class just like we can build a house from a blueprint. A class contains the characteristics and properties needed to create an object.

How to create a PHP class

Let us say you want to create a web based spaceship and aliens game using object oriented programming in Php. Your game will feature friendly spaceships and enemy spaceships, but all are spaceships. This means that the easiest way to begin would be by creating a general spaceship blueprint (class), from which we are going to create all the spaceships (objects) we need.

So, lets begin but creating a simple Spaceship class. Create a php file named spaceship.php and write the following code inside:


spaceship.php

// File: spaceship.php

class Spaceship {
// all class code is placed here
}

As you can see in the example above, creating a class is simple. To create a PHP class:

  • you use the class keyword
  • encapsulate all code within the class in {}.

The class keyword is lowercase but the name of the class, Spaceship, begins with an uppercase letter. The name of the class can begin with a lowercase letter, PHP will allow that. However, it is common practice to begin the class name with an uppercase letter in order to easily identify classes in code.

  • Class names cannot contain spaces or special letters, except for the underscore _ which is commonly used to connect two words together ( e.g. Enemy_ship).
  • Class names can be any combination of numbers and letters, although they must not begin with a number.

The Spaceship class we created above is fully functional class, although it useful yet. However you need to know that once you have created a class, you have defined a new data type.

What is an object?

An object is an instance of a class.

Since we previously said a class is a blueprint for generating objects, it follows that an object is a data type of its class. Objects are created by instantiating classes as follow:

How to create an object of a class

Remember this class?


class Spaceship {
// all class code is placed here
}

Now, let us use the Spaceship class (blueprint) to create spaceship objects. To do this, you use the new operator in conjunction with the class name as follows:

<?php


class Spaceship {

}

// Spaceship objects

$ship_one = new Spaceship;
$ship_two = new Spaceship;

?>

The new operator, when invoked with a class name, returns an instance of that class. For example, in the code above, we generated two Spaceship objects from the Spaceship class.

However the two objects, though they look identical, are different objects of the same class. Referring to our earlier example of blueprints and houses, $ship_one and $ship_two are like separate houses built from the same blueprint. They look identical in every way, but they are two different instances of the same class.

Just like every house has a unique address, every object created in a PHP script has its own unique identifier, throughout its own life. Let us see the unique identifiers of our objects.

<?php


class Spaceship {

}

// Spaceship objects

$ship_one = new Spaceship;
$ship_two = new Spaceship;
$command_ship = new Spaceship;

var_dump($ship_one);       //> object(Spaceship)#1 (0) { }
var_dump($ship_two);       //> object(Spaceship)#2 (0) { }
var_dump($command_ship);   //> object(Spaceship)#3 (0) { } 

?>

I created a third object in the example above. Passing the objects to var_dump(), produces useful information including the object’s internal identifier (after the hash sign).

Adding properties to a class

A class contains properties which are used to store data. Properties are also known as member variables. Properties include characteristics of the class. When an object is created, the operating system reserves a space in memory to hold the properties. The good thing is that the operating system handles memory management for us, including cleaning up properties that are no longer needed.

In Php, properties can hold many different data types without any need to define the data type of the data being stored. Php dynamically determines the type of data to be stored in a property when the first is added to the property.

Properties are created just like normal variables, with an initial $, followed by the property name. Property names can include alphabetic characters, numbers, and the and the underscore _, with no spaces are allowed. Properties are conventionally named using lowercase letters, though Php allows uppercase letters. Php is case-sensitive, which means $velocity and $Velocity are two different properties.

A property in a class is a defined in a similar way to a normal variable except that a property needs to be preceded the with a visibility keyword. The visibility keyword can be either be public, protected, or private. It determines the scope from which the property is visible. We shall deal with theses keywords later but for now we shall declare our properties using the public keyword.

Now let us add properties to our Spaceship class.

<?php

class Spaceship {
  public $velocity = 23;
  public $name = "HMS Sytech Royal";
  public $enemy = false;

}


$command_ship = new Spaceship;

var_dump($command_ship); 

//> OUTPUT:
//> object(Spaceship)#1 (3) { ["velocity"]=> int(23) ["name"]=> string(16) "HMS Sytech Royal" ["enemy"]=> bool(false) } 

?>

In the example above, I set up three properties and assigned a default value to each of the properties. Php then automatically determined the data type of each property based on the default values I set. To check that I then performed var_dump and the output object(Spaceship)#1 (3) { ["velocity"]=> int(23) ["name"]=> string(16) "HMS Sytech Royal" ["enemy"]=> bool(false) } showed that:

  • the first property is an integer
  • the second property is a string
  • the third property is a boolean

Every objects I instantiate from the Spaceship class will now contain the default data. The public keyword on each property ensures that I can access the property from outside of the object context.


Accessing property variables

Properties can be accessed from an object using the arrow notation $object->property_name as follows:

<?php

class Spaceship {
  public $velocity = 23;
  public $name = "HMS Sytech Royal";
  public $enemy = false;

}


$command_ship = new Spaceship;

print($command_ship->name);     //> HMS Sytech Royal


?>

Setting the property values

Values of properties can be assigned using the notation $object->property_name = value.

<?php

class Spaceship {
  public $velocity = 23;
  public $name = "HMS Sytech Royal";
  public $enemy = false;

}


$command_ship = new Spaceship;

// Setting a new value for the name property
$command_ship->name = "HMS Sydney Chako";

print($command_ship->name);       //> HMS Sydney Chako


?>

Adding properties dynamically

Php does not force you to declare all properties in the class. Properties can be added to an object dynamically to an object, as follows:

<?php

class Spaceship {
  public $velocity = 23;
  public $name = "HMS Sytech Royal";
  public $enemy = false;

}


$command_ship = new Spaceship;

// Adding a property dynamically

$command_ship->health = 87;

// Accessing the property

print($command_ship->health);       //> 87


?>

The Spaceship class had no health property but we added the health to the $command_ship object.

However, this method of assigning properties to objects is not recommended in object oriented programming. When you create a class you define a data type container that is a template of what an object should be like and what properties it should contain.