PHP OOP - Polymorphism - Activities

Last revision:

Activity

Create a File class that will be extended by the ImageFile class. 

The File class should have a $filename property that will be inherited by the ImageFile class.

Complete the ImageFile class and base yourself on the Book / Translator example from the Interfaces unit.

  • You will need to provide a basic File class (add any methods you want), and the Resizable and Croppable interfaces:
    • The Resizable interface specifies a resize() method.
    • The Croppable interface specifies a crop() method.

Create an ImageResizer class with a resizeObject() method that accepts any Resizable object and prints "Starting image resize...".

Create an ImageFile object and an ImageResizer object.

Make the ImageResizer's resizeObject() method call the resize() method on the ImageFile object it receives. The resize() method should print "resizing...".

When the resizing is done, the resizeObject() method should print "Done resizing.".

Expected output:

Starting image resize...
Resizing...
Done resizing.
Answer / solution
class File {

 public string $filename;

}

interface Resizable {

 public function resize();

}

interface Croppable {

 public function crop();

}

class ImageFile extends File implements Resizable, Croppable {

  public function resize() {
   print "Resizing...";
 }

 public function crop() {
   print "Cropping...";
 }

}

Class ImageResizer {

  public function resizeObject(Resizable $image) {
   print "Starting resize..." . PHP_EOL;
   $image->resize();
   print "Done resizing.";
 }

}

$mypicture = new ImageFile();
$mypicture->filename = "roberta.jpg";

$resizer = new ImageResizer();
$resizer->resizeObject($mypicture);