Unit IV (Objects)
Unit IV (Objects)
What is an Object?
An object is an instance of a class that groups related properties and methods.
An object is a self-contained unit of code that contains attributes
(variables) and behaviors (functions/methods) within a class.
Objects help organize and structure code in an efficient way.
Creating an Object
class Car {
public $brand;
public $color;
}
// Methods (functions)
public function method1() {
// Code for method
}
echo $object->sayHello();
// Output: Hello from an anonymous class!
Anonymous Class with Constructor
Anonymous classes can also have constructors just like regular classes.
$car = new class("Toyota") {
public $brand;
echo $car->getBrand();
// Output: This car is a Toyota
Constructor assigns the car's brand dynamically.
Method getBrand() returns the brand.
Anonymous Class Extending a Regular Class
An anonymous class can extend another class and override its methods.
class Greeting {
public function sayHi() {
return "Hi from the parent class!";
}
}
echo $greet->sayHi();
// Output: Hello from the anonymous class!
Output:
Is myTruck an instance of Truck? Yes
🔹 is_a($obj, "ClassName") → Checks if the object belongs to the specified class.