Object oriented programming (OOP) in PHP

Advantages of OOP in PHP

Applications written using OOP are usually relatively easy to use and understand, recommended especially for large projects, where more developers can work.

  • Because applications are real world objects based, using OOP we can create classes, a direct mapping of things,
    with properties and behaviors as the real world concepts.
  • Another benefit of OOP is code reuse. We can create and use classes in different applications, making application writing more simple and efficient.
  • Another major OOP advantage comes from the modularity of classes. For example if you discover a bug or want to change the code, you have to change it in one place inside the class, without having to go to more places.

Basic OOP Concepts

At the base of oop programming are the classes, properties, and methods.

Classes, how to create a class in PHP?

Classes are mapping of real world things. In the real world, objects have characteristics and behaviors. Let’s think of a vehicle, for example. A vehicle has a color, a weight, etc; those are its characteristics.
Also, a vehicle can go, stop, turn etc; Those are its behaviors.
Those characteristics are common to all vehicles, so using OOP You can create a class named “Vehicle”, to model all vehicles.

How to create a class in PHP?

First you need to create the class before you create an object belonging to that class. To create a class, you use PHP’s class keyword.

class Vehicle{

}
A common coding standard is to begin the class name with a capital letter, though it is not mandatory.

Objects, how to create an object in PHP?

What is an object?

An object is a specific instance of a class. For example, if you created a Vehicle class, you can
create an object called myVehicle that belongs to the Vehicle class. You can create as many objects as you like.

If a class has general characteristics, an object has specific values associated with class attributes. For example, if Vehicle class have color as an attribute, the object myVehicle will have specified color, such as “black”.

How to create an object in PHP?

It’s very simple to create an object in php. To create an object use the new keyword, followed by the name of the class that you want the object to belong to.

$firstVehicle = new Vehicle();
$secondVehicle = new Vehicle();

Even both objects are in the same class, they are independent of each othe and each is stored in its own variable.

Objects and references

As in most programming languages, In PHP objects are always passed by reference! If you want to assign by value instead, use the clone keyword.

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn’t contain the object itself as value anymore. It only contains an object identifier which allows to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object. Read more here about php objects and references.

For example at functions the arguments are passed default by value; that mean if the value of the argument within the function is changed, it does not get changed outside of the function. To allow a function to modify its arguments, they must be passed by reference (add & to the argument name in the function definition).

Properties

This characteristics of a class or object are known as its: properties. Properties are similar to variables because they have a name and a value.

Property Visibility

In PHP each property of a class can have one of three visibility levels:

  • Public property – can be accessed by any code, whether that code is inside or outside the class, from anywhere in your script
  • Private property – can be accessed only by code inside the class
  • Protected property – is slightly more permissive in the sense that it can be accessed by code inside the class and from any class that inherits the class.

How to declare and use properties inside a class?

To declare a property inside a class, first use the keyword for visibility level (public, private or protected), followed by the property’s name. When naming private properties and methods is a good coding practice to use an underscore after the $ sign, like $_name. It help us to identify private class members easier.

Also you can initialize properties at the time that you declare them, similar with variables.

Careful!! In PHP class member declarations require a visibility keyword (public, protected, or private) or the deprecated var keyword. When using var, the visibility will be public.

Unlike class method declarations, where the visibility keyword can be omitted, defaulting to public visibility.

If you omit the visibility keyword, you will get this error: Parse error: syntax error, unexpected ‘$type’ (T_VARIABLE), expecting function (T_FUNCTION)…

class Vehicle{
	$type = "car";
	public function start(){
		echo "The $this->type started";
	}
}
$myVehicle = new Vehicle();
$myVehicle->start();
//Result: Parse error: syntax error, unexpected '$type' (T_VARIABLE), expecting function (T_FUNCTION) ...

To access a property, use the variable storing the object, followed by “->”, followed by the property name.

class Vehicle{
	public $color;
	public $type;
}
$firstOb = new Vehicle();
$firstOb->color = "red";
$firstOb->type = "Auto";
echo "My first vehicle is {$firstOb->type} and have {$firstOb->color} color";

//Result: My first vehicle is Auto and have red color

How to use and access static properties?

Static members of a class are independent of any particular object derived from that class.

To create a static class property, just add static keyword before property name.

To access a static property use class name, followed by :: operator, followed by the property name.

How to use and access constants

To define a class constant, use the keyword cons. It’s a good practice to use all capitalized letters for the constant name.
To access a class constant use class name, followed by :: operator, followed constant name.

class Vehicle{
	public static $first_car_author = "Karl Benz";
	const FIRST_CAR_YEAR = 1885;
}
echo 'First car was made in '.Vehicle::FIRST_CAR_YEAR.' by '.Vehicle::$first_car_author.' from Germany';

//Result: First car was made in 1885 by Karl Benz from Germany

Methods

The behaviors of a class are known as its: methods . Methods are similar to functions in php; in fact, methods are defined usings the function statement.

The methods of a class, along with its properties, are known as members of the class.

Methods Visibility

In PHP each method of a class can have one of three visibility levels:

  • Public methods – can be called by any code, whether that code is inside or outside the class, from anywhere in your script
  • Private methods – can be called only by code inside the class
  • Protected methods – protected method can be called by other methods in the class, or in a class that inherits from the class.

How to create and use methods inside a class?

To create a method inside a class, first use the keyword for visibility level (public, private or protected), then the function keyword followed by the method name, followed by parentheses. The method code is inside curly braces.

!If the keyword for visibility is not specified, public is default.

To call a method, use the variable storing the object, followed by “->”, followed by the method name.

class Vehicle{
	public function start(){
		echo "The vehicle started";
	}
}
$myVehicle = new Vehicle();
$myVehicle->start();

//Result: The vehicle started

Methods can also have parameters and return values, just like functions.

How to access object properties from methods?

To access an object’s property from within a method of the same object, use the special variable $this, like $this->property. Also you can use $this to call an object’s method from within another method of the same object.

Examples:

class Vehicle{
	public $type = "car";
	public function start(){
		echo "The $this->type started";
	}
}
$myVehicle = new Vehicle();
$myVehicle->start();

//Result: The car started
class Vehicle{
	var $type = "vehicle";
	public function start(){
		if($this->type=="car"){
			echo "The car started";
		}else{
			echo "The vehicle started";
		}
	}
}
$firstVehicle = new Vehicle();
$firstVehicle->type = "car";
$firstVehicle->start();

//Result: The car started

How to use and access static methods?

To create a static class methods, just add static keyword before method name.
To call a static method, write the class name, followed by two colons, followed by the method name.

Static methods are useful when you want to add features that’s related to a class, but not to any particular object derived from that class.

/* Calculates the area and perimeter of a rectangle given two sides. */
class Rectangle{
	public $length;
	public $width;
	public function area(){
		echo "The rectangle area is: ". $this->length * $this->width;
	}
	public static function area_definition(){
		echo "Area of a rectangle is: lenght * width";
	}
}
//Call the static method
Rectangle::area_definition();

//Result: Area of a rectangle is: lenght * width

When to use self and when to use $this?

Use $this when you want to refer to the current object.
Use self when you to refer to the current class.

Careful! In conclusion, use $this->member for non-static members, use self::$member for static members.

/* Calculates the area and perimeter of a rectangle given two sides. */
class Rectangle{
	public static function area_definition(){
		echo "Area of a rectangle is: lenght * width";
	}
	public static function perimeter_definition(){
		echo "Perimeter of a rectangle is: 2(lenght + width)";
	}	
	public static function rectangle_properties(){
		echo "Each of the interior angles of a rectangle is 90'<br/>";
		echo "The opposite sides of a rectangle are parallel.<br/>";
		echo "The opposite sides of a rectangle are equal.<br/>";
		self::perimeter_definition();
	}
	
	
}
//Call the static method
Rectangle::rectangle_properties();

//Result: 
Each of the interior angles of a rectangle is 90'
The opposite sides of a rectangle are parallel.
The opposite sides of a rectangle are equal.
Perimeter of a rectangle is: 2(lenght + width)

Php class example, using __constructor, __destructor, __get and __set methods.

//Define the class
class Student{

    //Properties (attributes)
    private $name;
    private $age;

    //Run when an object is created
    public function __construct($name, $age){
        echo __CLASS__ . ' instantiated<br/>';
        $this->name = $name;
        $this->age = $age;
    }

    //Used for clean up, clossing connections
    public function __destruct(){
        echo 'Destructor run ...<br/>';    
    }

    //Methods (functions)

    //__get MAGIC METHOD
    public function __get($property){
        if(property_exists($this, $property)){
            return $this->$property;
        }
    }

    //__set MAGIC METHOD
    public function __set($property, $value){
        if(property_exists($this, $property)){
            $this->$property = $value;
        } 
        return $this;
    }

    public function sayHello(){
        return $this->name.' say Hello!';
    }

    /* public function setName($name){
        $this->name = $name;
    }*/

    /*public function getName(){
        return $this->name;
    }*/
}

//constructors, destructors, __get and __set magic methods
$student1 = new Student('Mike',24);
echo $student1->__get('name');
echo '<br>';
echo $student1->__get('age');
echo '<br>';
echo $student1->sayHello();
echo '<hr>';
$student2 = new Student('John',33);
echo $student2->sayHello();
echo '<hr>';
$student2->__set('name','Vin');
$student2->__set('age',45);
echo $student2->__get('name');
echo '<br/>';
echo $student2->sayHello();
echo '<hr>';

//Result:
Student instantiated
Mike
24
Mike say Hello!

Student instantiated
John say Hello!Vin
Vin say Hello!

Destructor run ...
Destructor run ...

Leave a Reply

Your email address will not be published. Required fields are marked *