Welcome to our PHP instanceof Operator tutorial! In this lesson, we'll explore one of the powerful tools PHP provides to check the type of a variable. Let's dive in! π³
The instanceof operator in PHP checks if an object is an instance of a specific class. It returns true if the object is an instance of the specified class or one of its parent classes, and false otherwise.
The instanceof operator is useful when you need to determine the type of an object, especially when dealing with inheritance. It allows you to write more flexible and maintainable code.
Here's the basic syntax of the PHP instanceof operator:
if ($object instanceof $class) {
// The object is an instance of the class
} else {
// The object is not an instance of the class
}Let's create a simple example. We'll define a Animal class and a Dog class that extends Animal. Then, we'll create an instance of the Dog class and check if it's an instance of the Animal class using the instanceof operator.
class Animal {
public function makeSound() {
echo "The animal makes a sound.\n";
}
}
class Dog extends Animal {
public function makeSound() {
echo "The dog barks.\n";
}
}
$dog = new Dog();
if ($dog instanceof Animal) {
echo "The dog is an instance of Animal.\n";
} else {
echo "The dog is not an instance of Animal.\n";
}
// Output: The dog is an instance of Animal.In this example, we'll create a Shape abstract class and several concrete classes that extend it. We'll then create an array of different shapes and iterate over it, checking the type of each shape using the instanceof operator.
abstract class Shape {
public function getArea() {
// Abstract method. Each concrete class should implement this method.
}
}
class Square extends Shape {
public $side;
public function __construct($side) {
$this->side = $side;
}
public function getArea() {
return pow($this->side, 2);
}
}
class Circle extends Shape {
public $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function getArea() {
return 3.14 * pow($this->radius, 2);
}
}
$shapes = [
new Square(5),
new Circle(3),
new Square(7),
new Circle(4)
];
foreach ($shapes as $shape) {
if ($shape instanceof Square) {
echo "This shape is a square with an area of " . $shape->getArea() . ".\n";
} elseif ($shape instanceof Circle) {
echo "This shape is a circle with an area of " . $shape->getArea() . ".\n";
}
}
// Output:
// This shape is a square with an area of 25.
// This shape is a circle with an area of 38.44.
// This shape is a square with an area of 49.
// This shape is a circle with an area of 50.24.What does the PHP `instanceof` operator do?
That's it for our PHP instanceof Operator tutorial! Now you're equipped to check the type of objects in your PHP code with confidence. πͺ Happy coding!