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.
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 answerHide 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
| Feature | In the example |
|---|---|
| Defined and created together | new class implements Logger { ... } |
| Implements an interface | Satisfies the Logger type that Report demands |
| Takes constructor arguments | new class (10) { ... } passes 10 to __construct() |
| Has no name | Nothing 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.
2079 · 5 marks
Describe an anonymous class using suitable example. [5]
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 answerHide 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
| Part | Role |
|---|---|
class Employee { ... } | Declares the blueprint |
private int $id and the other three | The attributes, hidden from outside code |
__construct() | Runs automatically at new and fills the attributes |
$this | The 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.
0 · 5 marks
How can you define class and object in PHP. Illustrate with example. [5]
Interfaces and class differences
2081 · 5 marks
How is class different from interface? Illustrate with an example. [5]
Constructors and initialization
2081 · 5 marks
Write a PHP program to demonstrate use of constructor. [5]
Class properties and attributes
2080 · 5 marks
Write a PHP program to access properties and methods of a class. [5]
Inheritance and class hierarchy
2080 · 5 marks
Write a PHP program to demonstrate the concept of inheritance. [5]
Make Unit 6 stick
Practice BIT301 with flashcards & quizzes