PHP PHP Object-Oriented Programming 3 — Questions and Answers
Question 1: What is a PHP trait primarily used for?
- Defining database schemas
- Reusing method implementations across classes without inheritance (Correct answer)
- Creating abstract interfaces
- Enforcing type safety
Correct answer: Reusing method implementations across classes without inheritance
Traits allow code reuse across multiple independent classes, solving the single-inheritance limitation in PHP.
Question 2: Which PHP magic method defines how an object behaves when cast to a string?
- __print()
- __string()
- __serialize()
- __toString() (Correct answer)
Correct answer: __toString()
__toString() is called automatically when an object is used in a string context, such as with echo.
Question 3: Which PHP magic method is triggered when reading an inaccessible or undefined property?
- __read()
- __access()
- __get() (Correct answer)
- __fetch()
Correct answer: __get()
__get() is invoked when attempting to read a property that is inaccessible or does not exist on the object.
Question 4: What keyword is used to indicate that a class fulfills an interface contract in PHP?
- extends
- uses
- fulfills
- implements (Correct answer)
Correct answer: implements
The implements keyword signals that a class will provide concrete definitions for all methods declared in the specified interface.
Question 5: What is late static binding in PHP accessed through?
- $this::
- self::
- parent::
- static:: (Correct answer)
Correct answer: static::
static:: uses late static binding, resolving to the class that was actually called at runtime rather than the class where the method was defined.
Question 6: Which keyword includes a trait inside a PHP class?
- import
- use (Correct answer)
- include
- extend
Correct answer: use
The use keyword inside a class body imports a trait's methods into that class.
What is a PHP trait primarily used for?