What specific features in PHP5 make it more suitable for object-oriented programming compared to PHP4?
PHP5 introduced several key features that make it more suitable for object-oriented programming compared to PHP4. These include improved support for visibility (public, private, protected), abstract classes, interfaces, and magic methods like __construct and __destruct. These features allow for better encapsulation, inheritance, and polymorphism, making it easier to write and maintain object-oriented code in PHP.
<?php
// Example demonstrating the use of visibility, abstract classes, and interfaces in PHP5
// Define an abstract class
abstract class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
// Abstract method that must be implemented by child classes
abstract public function getArea();
}
// Implement an interface
interface Drawable {
public function draw();
}
// Define a class that extends the abstract class and implements the interface
class Circle extends Shape implements Drawable {
private $radius;
public function __construct($color, $radius) {
parent::__construct($color);
$this->radius = $radius;
}
public function getArea() {
return pi() * pow($this->radius, 2);
}
public function draw() {
echo "Drawing a $this->color circle with radius $this->radius";
}
}
// Create an instance of the Circle class
$circle = new Circle('red', 5);
echo $circle->getArea(); // Output: 78.54
$circle->draw(); // Output: Drawing a red circle with radius 5
?>