Classes and Objects — PHP Technical Interview Questions & Answers

Classes and Objects

Classes and Objects

  • class Student { public $name; function __construct($name) { $this->name = $name; } } $s = new Student('Asha'); Object is one student. Class is the blueprint. $this is that object.
  • public/private/protected control who can touch fields. Keep fields private when you can.
  • Trap: $s.method() like JS. PHP is $s->method(). Trap: forgetting new.

Technical Interview Tip: new Student('Asha'); $s->name $this inside the class.

Code Examples for Classes and Objects

Classes and Objects — working example

<?php
class User {
  public function __construct(private string $name) {}
  public function hello(): string {
    return "Hello, {$this->name}";
  }
}
echo (new User("Ravi"))->hello();

Classes and Objects — constructor property promotion keeps simple classes short.

How to Explain Classes and Objects to an Interviewer

How do you make an object?

new ClassName() $obj->method()