Unit - 3 - PHP Question Bank
Unit - 3 - PHP Question Bank
Unit -III
1. Object Oriented Programming
a. Creating objects
b. Creating Classes
c. Setting Access to Properties and Methods
d. Constructors
e. Destructors
f. Inheritance
g. Overriding Methods
h. Overloading Methods
i. Autoloading Classes
b. Creating Classes:
Definition: A class in PHP is a blueprint for creating objects. It defines the properties
and methods that objects of that class will have.
Example Program:
class Animal {
public $species;
public function makeSound() {
echo "Animal sound!";
}
}
Explanation: The program defines an Animal class with a property $species and a
method makeSound(). This class can be used to create objects representing different
animals.
c. Setting Access to Properties and Methods:
Definition: Access modifiers (public, protected, private) control the visibility of
properties and methods within a class and its subclasses.
Example Program:
class Person {
public $name;
protected $age;
private $email;
}
Explanation: In this program, the Person class has properties with different access
modifiers. public properties can be accessed from outside the class, protected
properties can be accessed within the class and its subclasses, and private properties
are only accessible within the class itself.
d. Constructors:
Definition: Constructors are special methods in a class that are automatically called
when an object is created. They are used to initialize object properties.
Example Program:
class Book {
public $title;
public $author;
2
UNIT III PROGRAMMING IN PHP ACAS
3
UNIT III PROGRAMMING IN PHP ACAS
class Shape {
public function calculateArea() {
return 0;
}
}
4
UNIT III PROGRAMMING IN PHP ACAS
}
}
5
UNIT III PROGRAMMING IN PHP ACAS
});
6
UNIT III PROGRAMMING IN PHP ACAS
d. Creating Interfaces:
Definition: An interface defines a contract that classes must follow by implementing
its methods. An interface cannot be instantiated; it defines method signatures only.
Example Program:
interface Logger {
public function log($message);
}
7
UNIT III PROGRAMMING IN PHP ACAS
Explanation: In this program, the Logger interface defines a method log(). The
FileLogger class implements the Logger interface by providing an implementation
for the log() method.
e. Comparing Objects:
Definition: Objects can be compared using operators like == and ===, which
compare their references. You can also implement custom comparison logic using
methods like __equals().
Explanation: In this program, the Math class has a constant PI. You can access class
constants using the :: operator on the class name.
8
UNIT III PROGRAMMING IN PHP ACAS
class Person {
public $name;
i. Reflection:
Definition: Reflection is an advanced feature in PHP that allows you to examine and
manipulate the structure of classes, properties, and methods at runtime.
Example Program:
class MyClass {
public $property;