phpintermediate
PHP OOP
Classes, inheritance and interfaces
7 questions
By EZ4Code Team
1. What is the keyword to create an object in PHP?
new
create
make
instance
Explanation: Use new ClassName(args) to create an object, e.g. $obj = new Person();
2. How do you access the current object's properties/methods?
$this->
this.
self::
$this::
Explanation: Inside an instance method, use $this->prop to access instance properties/methods; self:: or static:: to access static members.
3. What is the syntax for class inheritance?
class Child extends Parent
class Child : Parent
class Child implements Parent
class Child(Parent)
Explanation: PHP uses extends to inherit a class (single inheritance); implements to implement interfaces (multiple allowed).
4. What is the visibility of public, protected, and private?
public: accessible anywhere; protected: class and subclasses; private: only this class
All three are the same
private can be accessed by subclasses
protected is only for this class
Explanation: public is visible globally; protected is visible to this class and its subclasses (and parent); private is visible only to this class and cannot be accessed by subclasses.
5. What is the difference between an interface and an abstract class?
An interface only declares methods without implementation; an abstract class can contain implementations and abstract methods, and can be inherited
They are exactly the same
Abstract classes cannot have implementations
Interfaces can have implemented methods
Explanation: An interface only declares method signatures (no implementation); a class can implement multiple interfaces; an abstract class can contain concrete implementations and abstract methods, with single inheritance only.
6. What does the static keyword do?
Declares static properties/methods that belong to the class rather than instances, accessed via ::
Declares constants
Declares private members
Declares abstract methods
Explanation: Properties/methods declared with static belong to the class itself and can be accessed without instantiation via ClassName::$prop or self::/static::.
7. What are the requirements for an abstract method in PHP?
Only a declaration without implementation, the enclosing class must be abstract, and subclasses must implement it
Can have an implementation
Can be defined in a non-abstract class
Subclasses may not implement it
Explanation: Methods modified with abstract have only a signature and no implementation; the enclosing class must be declared abstract, and subclasses must implement all abstract methods before they can be instantiated.