PHP Class and Object Flashcards
What is a class in PHP?
A class is a blueprint for creating objects in PHP. It defines properties (attributes) and methods (functions) that the objects created from the class will have. Classes encapsulate data and behavior together.
How is an object created in PHP?
An object is created using the new keyword followed by the class name:
$object = new ClassName();
What are constructor and destructor in PHP?
Constructor: A special method called automatically when an object is created. It is defined using construct().
Destructor: A special method called automatically when an object is destroyed. It is defined using destruct().
What is an interface in PHP?
An interface in PHP is a contract that defines a set of methods that a class must implement. It does not contain any implementation details, only method declarations. Interfaces allow for multiple inheritance, meaning a class can implement multiple interfaces.
What is the final keyword in PHP and when is it used?
The final keyword is used to prevent class inheritance or method overriding. When a class is declared as final, it cannot be extended. When a method is declared as final, it cannot be overridden in derived classes.
Create a ‘stud’ class in PHP to take RollNo, Name, and MobNo of 10 students and display it back.
class Stud {
public $rollNo;
public $name;
public $mobNo;
public function \_\_construct($rollNo, $name, $mobNo) { $this->rollNo = $rollNo; $this->name = $name; $this->mobNo = $mobNo; } public function display() { echo "Roll No: $this->rollNo, Name: $this->name, Mobile No: $this->mobNo<br>"; } }
// Create an array to hold student objects
$students = [];
for ($i = 0; $i < 10; $i++) {
$students[] = new Stud(“Roll” . ($i + 1), “Student” . ($i + 1), “123456789” . $i);
}
// Display student details
foreach ($students as $student) {
$student->display();
}
What are the different types of visibility (access modifiers) in PHP?
Public: Accessible from anywhere (inside and outside the class).
Protected: Accessible within the class and by derived classes.
Private: Accessible only within the class itself.
What is the difference between an abstract class and an interface in PHP?
Abstract Class:
Can have both abstract and concrete methods.
Can have properties and methods with visibility (public, protected, private).
Supports single inheritance.
Interface:
Can only have method declarations (no implementation).
Cannot have properties.
Supports multiple inheritance (a class can implement multiple interfaces).
What are the advantages of object-oriented programming (OOP)?
Encapsulation: Bundles data and methods, restricting access to internal states.
Inheritance: Allows classes to inherit properties and methods from other classes, promoting code reuse.
Polymorphism: Enables methods to do different things based on the object