Force someone to subclass to execute interface methods

I am wondering how to make subclasses implement this interface method.

Let's say I have the following classes:

interface Serializable { public function __toString(); } abstract class Tag // Any HTML or XML tag or whatever like <div>, <p>, <chucknorris>, etc { protected $attributes = array(); public function __get($memberName) { return $this->attributes[$member]; } public function __set($memberName, $value) { $this->attributes[$memberName] = $value; } public function __construct() { } public function __destruct() { } } 

I would like to force any subclass of the Tag class to implement the Serializable interface. For example, if I am a “paragraph class”, it will look like this:

 class Paragraph extends Tag implements View { public function __toString() { print '<p'; foreach($this->attributes as $attribute => $value) print ' '.$attribute.'="'.$value.'"'; print '>'; // Displaying children if any (not handled in this code sample). print '</p>'; } } 

How to force a developer to force his "Paragraph" class to implement methods from the "Serializable" interface?

Thanks for taking the time to read.

+4
source share
3 answers

Just implement the abstract class interface:

 interface RequiredInterface { public function getName(); } abstract class BaseClass implements RequiredInterface { } class MyClass extends BaseClass { } 

Running this code will result in an error:

Fatal error: MyClass class contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (RequiredInterface :: GetName)

This requires the developer to code the RequiredInterface methods.

+5
source

PHP code example:

 class Foo { public function sneeze() { echo 'achoooo'; } } abstract class Bar extends Foo { public abstract function hiccup(); } class Baz extends Bar { public function hiccup() { echo 'hiccup!'; } } $baz = new Baz(); $baz->sneeze(); $baz->hiccup(); 

It is possible that an abstract class extends Serializable, since abstract classes should not be base classes

+1
source

This adds __construct either your Paragraph class, which checks to see if Serializable is implemented.

 class Paragraph extends Tag implements View { public function __construct(){ if(!class_implements('Serializable')){ throw new error; // set your error here.. } } public function __toString() { print '<p'; foreach($this->attributes as $attribute => $value) print ' '.$attribute.'="'.$value.'"'; print '>'; // Displaying children if any (not handled in this code sample). print '</p>'; } } 
0
source

All Articles