Implementing Multiple Interfaces

In Java, a Class can Implement multiple Interfaces.

Is the same true for PHP5?

TomTees

Yes.


class DoubleLinkedList implements Cloneable, Serializiable {
  // etc..
}

Okay, thanks guys!

TomTees

In PHP a class can only extend one other class though, not multiple (sadly). If you need to extend several classes you can do it like so:


class A {
}
class B extends class A {
}
class C extends class B {
}
// etc ...

That way class C extends both class A and B. This can get messy real quick though; use with care :slight_smile:

Can you Extends multiple classes in other languages like Java and C++?

Is it bad design to want to extend a class multiple times anyways?

TomTees

Java: no, C++: yes

As for bad design, well that depends on what you want to do. The principle in itself is not bad, but as with a lot of things it can be used wrongly.

As a general rule of thumb I’d say single-level inheritance is OK, two-level inheritance is tolerable, three-level inheritance is very questionable, and if you want to go even further than that you should probably go back to the drawing board :slight_smile:

Last I heard mixins are planned for PHP 6. So when 6 comes out multiple inheritance will be possible using mixins.

:weee:

More precisely, traits have been committed to trunk. That may end up becoming 5.4 or 6. I’m guessing the former.

Traits are a form of mixins, but they are resolved at static time. I think this matches better with php’s class model.

See this page for a detailed discussion: http://wiki.php.net/rfc/horizontalreuse

Cerium’s example is correct; and all classes must explicitly be defined as interface, to implement it.


<?php
interface Cloneable
{
}

interface Serializiable
{
}

class DoubleLinkedList implements Cloneable, Serializiable {
}

$dll = new DoubleLinkedList();
?>

Many MVC’s frameworks do not support interfaces either. So if you plan on making something and then porting it over to an MVC framework be careful. Kohana 3 does allow the use of interfaces.

Most others only support abstract classes, because at the core many MVC frameworks still support php 4.

You mean faux abstract classes, PHP 4 doesn’t have the “abstract” keyword or enforcement.