In this lesson, you will learn about the basic features of object-oriented programming with PHP. The OOP is not a new way to write code, but it is entirely a different approach to writing code. With procedural language, the focus is on the actions whereas in OOP the focus in on the nouns.

PHP and Object Oriented Programming

Object-oriented programming begins with classes and objects.

PHP and Classes

A class is a more generalized definition of an object. Think of a class as a blueprint of something. An object is a specific implementation of that thing. Think of an object like a house built using the design (class).

A class declaration begins with the keyword class, followed by the name of the class. The class name cannot be a reserved keyword and must start with a letter or underscore. After the class name, the curly braces contains the class definition.

<?php 

	class myClass{
		//class properties and methods go here
	
	}
?>

After creating the class, an object can be instantiated using the new keyword.

$obj = new myClass();

To see the contents of the class, use var_dump($obj);

The $this attribute

$this is a pseudo-variable. It is a reference to the object being called.

In the following example, we create two methods:
getName() and setName() to get and set the property of a class.

<?php
class person
{
    var $name;
    function setName($new_name)
    {
        $this->name = $new_name;
    }
    function getName()
    {
        return $this->name;
    }
}
?>

Creating an object in PHP

You can create as many objects as you want from a class. PHP lets you create an object using the new keyword. It also provides you with two magic methods __construct() and __destruct() which is executed when a new object is created, or an existing object is being destroyed.

<?php
class person
{
    public function __construct()
    {
        echo "The class " . __CLASS__ . " is created!";
    }
    public function __destruct()
    {
        echo "The class " . __CLASS__ . " Is destroyed";
    }
}
$john = new person();
?>

The output:

The class person is created!
The class person is destroyed

OOP Principles

There are three major principles of object-oriented programing.

Encapsulation

It refers to a concept where actual implementation is hidden from the user. A class is supposed to do everything you need it to do without you ever know how it is being done. The encapsulation has many benefits.

  1. It reduces software development complexity. Your team members can work on individual objects or methods without being informed about everything else.
  2. It protects the internal state of an object
  3. It lets you change the internal implementation of the class anytime without breaking the whole code or class

The properties and methods in a class are defined as public, protected, or private.

Anyone who can access the class can access a public variable or method. This is by-default behavior of class members.

// Public
public $variable;
public function doSomething() {
// ...
}

To restrict the accessibility of the class members, you can declare them as private or protected.

A protected variable or method can be accessed only by the class member of the same class or a child class.

// Private
private $variable;
private function doSomething() {
// ...
}

A private variable or method can only be accessed in the class in which it is declared, as well as in the class that extends that class. Protected members are not accessible outside of these two classes.

// Protected
protected $variable;
protected function doSomething() {
// ...
}

Example of Encapsulation in PHP

<?php
class MyClass
{
    public $public = 'Public ';
    protected $protected = 'Protected ';
    private $private = 'Private ';
    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}
$obj = new MyClass();
$obj->printHello(); // Shows Public, Protected and Private
echo "<br/>";
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
?>

The output

Inheritance

OOP lets you create a high-level abstract class that is referred to as the parent class which can be inherited by multiple child classes when needed. In PHP, you can use the extends keyword to inherit the functionality of the base or parent class.

Example of Inheritance in PHP

<?php

class Animal
{
    
    public $name;
    
    public $breed;
    
    public function __construct($name, $breed)
    {
        
        $this->name = $name;
        
        $this->breed = $breed;
        
    }
    
    public function greet()
    {
        
        return "Hello ! My name is " . $this->name . " and I am a " . $this->breed . "<br>";
        
    }
    
} // class Animal

class Dog extends Animal
{
    
    public function play()
    {
        
        return $this->name . " loves to play.<br>";
        
    }
    
} //class Dog

$dog = new Dog("Max", "Labra");

echo $dog->greet();

echo $dog->play();
?>

If you need to prevent child classes from overriding methods, prefix the final keyword.

<?php

class A{

final function add($x, $y){echo $x+$y;}
}

class B extends A{

function add($x, $y){$c = $x+$y; echo $c; }
}
?>

Polymorphism

Polymorphism describes a pattern in which classes can have a common interface while behaving differently. In PHP interface is similar to a class except that it does not contain any code. The interface is to define method names and arguments, but not the contents of the methods.

To declare an interface, use the interface keyword and is attached to a class using the implements keyword. Methods can be defined in the interface just like in a class, except have no content within the braces.

Example of Polymorphism in PHP

<?php
interface My_Interface
{
    
    public function fun();
}

class MyClass implements My_Interface
{
    
    public function fun()
    {
        
        //code goes here.
    }
}
?>

Abstraction

An abstract class cannot be instantiated, and you can only inherit this class. If you inherit from an abstract class, all abstract methods in the parent’s class need to be defined by the child with the same visibility. PHP doesn’t allow you to have an abstract method inside a non-abstract class.

Example of Abstraction in PHP

<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<style>
*{box-sizing:border-box;}
body{font-family: 'Open Sans', sans-serif; color:#333; font-size:14px; padding:100px;}
</style>
<body>
<div class="form_box shadow">
<?php

class Pet
{
    
    var $name;
    function __construct($name)
    {
        $this->name = $name;
    }
}

interface Talkative
{
    public function speak();
}

class Dog extends Pet implements Talkative
{
    function speak()
    {
        return "Woof, woof!";
    }
    
    function fetch()
    {
        return 'Catching the stick <br>';
    }
}

class Cat extends Pet implements Talkative
{
    function speak()
    {
        return "Meow...";
    }
}

$Pets = array(
    new Dog('Max'),
    new Cat('Snow')
);

foreach ($Pets as $Pet) {
    print $Pet->name . " says: " . $Pet->speak() . '<br>';
    if ($Pet instanceof Dog)
        echo $Pet->fetch();
}

?>

</div>
</body>

</html>

PHP and JSON Tutorial Home

 

Last modified: May 1, 2019