OOP

by Gisle Hannemyr

This chapter ....

Table of contents

Introduction

Object-oriented programming (OOP)is a programming style in where we group all of the variables (properties) and functions (methods) of a particular topic into a single class.

OOP is considered to be more advanced and efficient than the procedural style of programming. This efficiency stems from the fact that it supports better code organization, provides modularity, and facilitates code reuse.

External links to background materials:

Classes, interfaces and traits

Inheritance is a major concept in OOP. It allows properties and methods of an existing class to be reused in a new class. There are two types of inheritance: Single and multiple inheritance. In single inheritance, a subclass inherits from a single superclass whereas, in multiple inheritance, a subclass inherits from multiple superclasses. Multiple inheritance is more complex than single multiple inheritance.

PHP, like Java and C#, is a single inheritance language. C++ is a multiple inheritance language.

In the procedural paradigm, all of the functions and variables inhabit the global scope. Methods may be used just by calling their name. Variables can be inspected by name. In the OOP paradigm, classes are just templates, and their functions (methods) and varaibleds (properties) need to be created (instantiated) as objects before they can be used. As many objects as one like can be instantiated from the same class, and each object may have its own state.

Class

A class is a programmer-defined data type, which includes properties and methods.

We declare the class with the class keyword.

To name the class, it is customary to use a singular noun that starts with a capital letter. If the class name contains more than one word, we capitalize each word (upper camel case). For example: AfricaTour.

The naming convention for properties is to start the property name with a dollar sign followed by a lower case letter. If the name contains more than one word, all of the words, except for the first word, start with an upper case letter. For example: $hasCamera.

class Mobile {
  // Variables.
  public var $name;
  public var $price;
  public var $hasCamera = true;
  // Public methods.
  public function setName($name) {
    $this->name = $name;
  }
  public function setPrice($price) {
    $this->price = $price;
  }
  public function getSpecs() {
    echo 'Name: ' . $this->name . ', price: ' . $this->price . '.';
  }
}

To create an instance (object) of a class we to use the new operator. he process of creating an object is also known as instantiation.

We can then interact with the instance by calling its methods. Such calls may change or examine its state.

$samsung = new Mobile();
$samsung->setName( 'Samsung S7');
$samsung->setPrice( 'USD 500');
$iphone = new Mobile();
$iphone->setName( 'Iphone 7');
$iphone->setPrice( 'USD 599');
$samsung->getSpecs();
Name: Samsung S7, price USD 500.
$iphone->getSpecs();
Name: Iphone 7, price USD 599.

A child class is created with the extends keyword. It inherits the properties and methods of the parent class. This is called inheritance.

The child class can extend the superclass with more methods, and it may override the methods and properties of the superclass.

class MoreText extends Mobile {
  public function getSpecs() {
    echo 'The device named ' . $this->name . ' will cost you ' . $this->price . '.';
  }
}

Example:

$Iphone2 = new MoreText();
$Iphone->setName( 'Iphone 7');
$Iphobe->setPrice( 'USD 599');
$Iphone2->getSpecs();
The device named Iphone 7 will cost you USD 599.

Source: https://www.brainbell.com/php/constants.html

A class holds the methods and properties that are shared by all of the objects that are created from it.

Although the objects share the same code, they can behave differently because they can have different values assigned to them.

Interface

Interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are implemented.

Interfaces are defined in the same way as a class, but with the interface keyword replacing the class keyword and without any of the methods having their contents defined.

Example [not tested]:

interface iTemplate {
  public function setVariable($name, $var);
}

A class that implements the interface is defined using the implements keyword:

class Template implements iTemplate
{
  private $vars = array();

  public function setVariable($name, $var) {
    $this->vars[$name] = $var;
  }
}

Trait

Source PHP: Traits.

Traits are a mechanism for code reuse in a single inheritance language such as PHP. A trait is intended to reduce some limitations of single inheritance by enabling a developer to horizontally reuse sets of methods freely in several independent classes living in different class hierarchies. I.e.: Traits allow you to create code that can be reused freely in several independent classes living in different class hierarchies.

noteOnly use a trait when multiple classes share the same functionality. It is pointless to use a trait to provide functionality for a single class. Instead implement the trait's functionality as a private method inside the class.

A trait is an addition to traditional inheritance and enables use of methods without requiring inheritance.

Traits are defined in the same way as a class, but with the trait keyword replacing the class keyword and having all its methods implemented.

A trait is very similar to a mixin. It is really just a reusable code snippet, where functionality that can be shared between multiple classes, including classes of different structure and origin.

The semantics of the combination of traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance.

Example [not tested]:

class BaseWorld {
  public function sayHelloworld() {
    echo 'Hello World!';
  }
}

class BaseDaddy {
  public function sayHellodaddy() {
    echo 'Hello daddy!';
  }
}

trait tSaymore {
  function sayHereiam() {
    echo 'Here I am.';
  }
}

class childHello extends BaseWorld {
  use tSaymore;
  sayHelloworld();
  sayHereIAm();
}

class childWorld extends BaseDaddy {
  use tSaymore;
  sayHellodaddy();
  sayHereIAm();
}

Here, we gain access to the methods of the base classes by extending them (inheritance), and we get access to the functionality of the trait by telling the child class to “use” it.

Visibility

The visibility of a method, a property or a constant defined inside a class can be defined by prefixing the declaration with the keywords public, protected or private.

If you don't use any visibility modifier, the property/method will be public.

See alsoSee also PHP: Visibility. This blog post by Fabien Potencier: Pragmatism over Theory: Protected vs Private is also helpful towards understanding usage.

Final word

[TBA]


Last update: 2021-03-11 [gh].