6 Object Oriented Programming

Web Technology II · Unit 6

Object Oriented Programming

Exam-focused notes for Object Oriented Programming (Web Technology II, BIT301): what the TU syllabus asks and how it has actually been tested, with 8 solved past questions from this unit.

Object Oriented Programming in short

Object oriented programming (OOP) organises code around objects that combine data and behaviour. PHP supports classes, inheritance, interfaces and more.

Object Oriented Programming: notes

Class and object definition

A class is a blueprint. An object is a real item made from that blueprint. A class holds properties (data) and methods (functions).

<?php
class Employee {
    public $name;
    public $salary;

    public function show() {
        echo "$this->name earns $this->salary";
    }
}

$e = new Employee();
$e->name = "Ram";
$e->salary = 50000;
$e->show();

$this is a special variable that refers to the current object. The arrow -> is used to reach a property or method.

Object instantiation

Instantiation means creating an object from a class with the new keyword. Each object has its own copy of the properties.

<?php
$a = new Employee();
$b = new Employee();
$a->name = "Sita";
$b->name = "Hari";      // separate from $a
$c = $a;                // $c points to the same object as $a
$d = clone $a;          // $d is a new copy
  • Objects are passed by handle, so $c = $a does not copy the object.
  • Use clone to make a real copy.
  • instanceof tests the class: $a instanceof Employee.
  • new can also be used with a class name in a variable: new $className().

Class properties and attributes

Properties hold the state of an object. They can have a visibility, a type and a default value. A static property belongs to the class, not to one object, and a constant never changes.

<?php
class Account {
    public string $owner = "";
    private float $balance = 0;
    public static int $count = 0;
    const BANK = "Nepal Bank";

    public function __construct() {
        self::$count++;
    }
}
echo Account::BANK;     // class constant
echo Account::$count;   // static property

Static members are reached with ::. Inside the class use self:: for the same class.

What this unit covers

  • Class and object definition
  • Object instantiation
  • Class properties and attributes
  • Class methods and access
  • Constructors and initialization
  • Inheritance and class hierarchy
  • Interfaces and class differences
  • Anonymous classes
  • Encapsulation principles

Anonymous classes

2082 · 5 marks

What is anonymous class? Write a program to demonstrate the use of anonymous classes. [5]

Show solved answer

Anonymous classes in PHP

An anonymous class is a class that is defined and instantiated in a single expression and is never given a name. PHP has supported them since version 7, written as new class { ... }. The value of the expression is an object, so the definition and the object creation happen together, which suits a case where an implementation is needed exactly once and a named class kept in its own file would only add noise.

An anonymous class is an ordinary class in every other respect. It may accept constructor arguments, may extend one class, may implement any number of interfaces, and may use traits. Two anonymous classes written at two different places in the code are always distinct classes even when their bodies are identical, and because the class has no name it cannot be referred to, extended or reused elsewhere.

The general form is:

$object = new class ($constructorArguments) extends SomeClass implements SomeInterface {
    // properties and methods
};

A program that uses one

<?php
interface Logger
{
    public function log(string $message): void;
}

class Report
{
    private Logger $logger;

    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
    }

    public function run(string $title): void
    {
        // the title may come from $_GET, so it is escaped before it is written to the
        // page, otherwise a title containing a script tag would run in the browser
        echo "<h3>" . htmlspecialchars($title, ENT_QUOTES, "UTF-8") . "</h3>";
        $this->logger->log("The report " . $title . " was generated.");
    }
}

// an anonymous class supplying a one off implementation of the Logger interface
$report = new Report(new class implements Logger {
    public function log(string $message): void
    {
        echo "<p>LOG: " . htmlspecialchars($message, ENT_QUOTES, "UTF-8") . "</p>";
    }
});

$report->run("Monthly sales");

// an anonymous class that takes a constructor argument of its own
$counter = new class (10) {
    public function __construct(private int $value) {}

    public function next(): int
    {
        return ++$this->value;
    }
};

echo "<p>Next value: " . $counter->next() . "</p>";
?>

The browser receives the heading Monthly sales, then the line LOG: The report Monthly sales was generated., and finally Next value: 11.

What the example shows

FeatureIn the example
Defined and created togethernew class implements Logger { ... }
Implements an interfaceSatisfies the Logger type that Report demands
Takes constructor argumentsnew class (10) { ... } passes 10 to __construct()
Has no nameNothing else in the program can refer to either class

Anonymous classes are used for test doubles, for small strategy or callback objects, and for adapters that exist only to satisfy a type hint. A closure would serve when only one piece of behaviour is needed, but an anonymous class is the right tool when the interface being satisfied has several methods or when the object must carry state between calls.

Open this answer on its own page →

2079 · 5 marks

Describe an anonymous class using suitable example. [5]

An anonymous class is a class written directly at the place where its single object is needed, with no name attached to it. PHP creates the class and the object in one expression, new class { ... }, a form available since PHP 7. Before that the only way to supply behaviour inline was a closure, w...

Open this answer on its own page →

Class and object definition

2082 · 5 marks

Write a program to create a class Employee with some attributes and methods. Create an object of the class and display some output using any method in the class. [5]

Show solved answer

An Employee class in PHP

A class is the blueprint that describes what an employee record holds and what can be done with it, and an object is one concrete employee built from that blueprint. In PHP the properties are declared with a visibility keyword, the constructor is the magic method __construct(), and inside any method the current object is referred to as $this, with -> used to reach a property or call a method.

<?php
class Employee
{
    private int    $id;
    private string $name;
    private string $department;
    private float  $salary;      // monthly salary

    public function __construct(int $id, string $name, string $department, float $salary)
    {
        $this->id         = $id;
        $this->name       = $name;
        $this->department = $department;
        $this->salary     = $salary;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function annualSalary(): float
    {
        return $this->salary * 12;
    }

    public function giveRaise(float $percent): void
    {
        $this->salary += ($this->salary * $percent) / 100;
    }

    public function display(): string
    {
        // the name and department are stored values that end up inside an HTML page,
        // so they are escaped here, since a value held in the database may contain
        // characters such as < or & that would otherwise be read as markup
        $safeName = htmlspecialchars($this->name, ENT_QUOTES, "UTF-8");
        $safeDept = htmlspecialchars($this->department, ENT_QUOTES, "UTF-8");

        return "<p>Employee ID: " . $this->id . " "
             . "Name: " . $safeName . " "
             . "Department: " . $safeDept . " "
             . "Monthly salary: Rs. " . number_format($this->salary, 2) . "</p>";
    }
}

// creating an object of the class
$emp = new Employee(101, "Ram Sharma", "IT", 50000);

echo $emp->display();
echo "<p>Annual salary: Rs. " . number_format($emp->annualSalary(), 2) . "</p>";

$emp->giveRaise(10);
echo "<p>After a 10 percent raise:</p>";
echo $emp->display();
?>

The page produced is:

Employee ID: 101
Name: Ram Sharma
Department: IT
Monthly salary: Rs. 50,000.00

Annual salary: Rs. 600,000.00

After a 10 percent raise:
Employee ID: 101
Name: Ram Sharma
Department: IT
Monthly salary: Rs. 55,000.00

The parts of the class

PartRole
class Employee { ... }Declares the blueprint
private int $id and the other threeThe attributes, hidden from outside code
__construct()Runs automatically at new and fills the attributes
$thisThe object the method is currently working on
annualSalary(), giveRaise(), display()The methods, the behaviour of the object
new Employee(101, "Ram Sharma", "IT", 50000)Creates one object from the blueprint

Declaring the attributes private is what makes giveRaise() worth writing: outside code cannot reach in and set an arbitrary salary, it must go through a method that applies the rule. PHP 8 allows the same class to be written more briefly with constructor property promotion, where public function __construct(private int $id, private string $name) declares and assigns the properties in one line.

Open this answer on its own page →

0 · 5 marks

How can you define class and object in PHP. Illustrate with example. [5]

A class is a blueprint or template that defines the properties (attributes) and behaviors (methods) of objects. It is a user-defined data type that encapsulates data and functions together. Syntax: An object is an instance of a class. When a class is defined, no memory is allocated; memory is all...

Open this answer on its own page →

Interfaces and class differences

2081 · 5 marks

How is class different from interface? Illustrate with an example. [5]

A class is a complete blueprint: it declares what an object holds and supplies the bodies of the methods that act on it. An interface is only a contract: it names the methods an implementing class must provide, without saying how any of them work. A class answers how, an interface answers what. P...

Open this answer on its own page →

Constructors and initialization

2081 · 5 marks

Write a PHP program to demonstrate use of constructor. [5]

A constructor is a special method in a class that is automatically called when an object is created. In PHP, the constructor method is defined using construct(). --- --- --- Feature Description ------ construct() Special method called automatically on object creation

Open this answer on its own page →

Class properties and attributes

2080 · 5 marks

Write a PHP program to access properties and methods of a class. [5]

Concept Syntax Description --------- Define a class class ClassName { } Blueprint for objects Create an object $obj = new ClassName(); Instance of a class Access property $obj-propertyName Using arrow operator - Access method $obj-methodName() Using arrow operator - Access inside class $this-prop...

Open this answer on its own page →

Inheritance and class hierarchy

2080 · 5 marks

Write a PHP program to demonstrate the concept of inheritance. [5]

Inheritance is an OOP concept where a child class (derived class) acquires the properties and methods of a parent class (base class) using the extends keyword in PHP. --- --- --- Concept Description ------ extends Used to inherit parent class into child class parent::construct() Calls the constru...

Open this answer on its own page →