PHP PHP Object-Oriented Programming 1 — Questions and Answers
Question 1: Which keyword is used to define a class in PHP?
- object
- define
- class (Correct answer)
- struct
Correct answer: class
The class keyword is used to declare a class definition in PHP.
Question 2: What does $this refer to inside a PHP class method?
- The parent class
- The current object instance (Correct answer)
- The class itself
- The most recently created object
Correct answer: The current object instance
$this is a pseudo-variable that refers to the current object (instance) inside a method.
Question 3: Which keyword is used to create a new instance of a class in PHP?
- create
- instance
- new (Correct answer)
- make
Correct answer: new
The new keyword instantiates a class, calling its constructor and returning the object.
Question 4: What is the name of the special method automatically called when an object is created in PHP?
- __init()
- __start()
- __new()
- __construct() (Correct answer)
Correct answer: __construct()
__construct() is the PHP magic method that serves as the constructor, called automatically on object instantiation.
Question 5: Which keyword enables one PHP class to inherit from another?
- inherits
- extends (Correct answer)
- implements
- uses
Correct answer: extends
The extends keyword creates an inheritance relationship, giving the child class access to the parent's public and protected members.
Question 6: What visibility modifier restricts a property or method to the class itself only?
- public
- protected
- internal
- private (Correct answer)
Correct answer: private
private members are accessible only within the class that defines them, not from subclasses or outside code.
Which keyword is used to define a class in PHP?