PHP interface resizable: Resizing functionality in the square class
4. Resizable Interface with Square Class
Write a PHP interface called 'Resizable' with a method 'resize()'. Implement the 'Resizable' interface in a class called 'Square' and add functionality to resize the square.
Sample Solution:
PHP Code :
<?php
interface Resizable {
public function resize($percentage);
}
class Square implements Resizable {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function resize($percentage) {
$this->side = $this->side * ($percentage / 100);
}
public function getArea() {
return pow($this->side, 2);
}
public function getSide() {
return $this->side;
}
}
$square = new Square(10);
echo "Initial Side Length: " . $square->getSide() . "</br>";
$square->resize(60); // Resize the square to 60% of its original size
echo "Resized Side Length: " . $square->getSide() . "</br>";
echo "Area: " . $square->getArea() . "</br>";
?>
Sample Output:
Initial Side Length: 10 Resized Side Length: 6 Area: 36
Explanation:
In the above exercise -
- The Resizable interface defines a contract with a single method resize(). Any class that implements this interface must implement the resize() method.
- The "Square" class implements the Resizable interface and provides its own implementation for the resize() method. It also has a private property $side to represent the sides of the square.
- The resize() method in the Square class resizes the square by adjusting its side length based on the provided percentage.
- The getArea() method calculates and returns the square area using the formula: side * side.
- The getSide() method returns the current square side length.
Flowchart:


For more Practice: Solve these Related Problems:
- Write a PHP interface that defines a resize method and implement it in a Square class that changes its side length by a given factor.
- Write a PHP program that tests the resizing method by increasing and decreasing the dimensions of a Square object repeatedly.
- Write a PHP class that implements the Resizable interface and adds validation to prevent resizing to a negative size.
- Write a PHP script to simulate batch resizing of multiple Square objects and display their new areas.
Go to:
PREV : Abstract Shape with Subclasses.
NEXT : Vehicle Class.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.