3

I've heard that you can't use extend twice.

I have two classes:

Base32 and SecureRandom

Which I need for TOTP.

How can I use both of these for it?

Steven
  • 43
  • 1
  • 3

3 Answers3

5

Use interfaces or composition (include an instance of one of the classes as a member variable of the class).

Interfaces allow you to define prototypes for the methods in a class. A class then implements that interface and must define a method for each prototype in the interface. You can only inherit directly from one class (extends) but you can implements an arbitrary number of interfaces.

If you find that interfaces don't fit your task well, just use composition.

Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
  • 1
    Composition is definitely the way to go in this circumstance. Just because you want a class to inherit functionality of another object doesn't mean it is a good fit for inheritance. – John Cartwright Apr 25 '11 at 14:29
2

Take a look into PHP5.4 Traits they kind of solving problem of multiple extends.

Combine them with interfaces to get instanceof functionality.

For example:

interface ClientAwareInterface {
    public function setClient($client);
}

trait ClientAwareTrait {
    protected $client;

    public function setClient($client)
    {
        $this->client = $client;
    }
}

class Shop implements ClientAwareInterface extends SomeClass {
    use ClientAwareTrait; // use our trait to implement interface methods
    use OtherTrait;
}

$shop = new Shop();
if($shop instanceof ClientAwareInterface) {
    $shop->setClient('test');
    var_dump($shop); 
}

Result would be:

object(Shop)[1]
  protected 'client' => string 'test' (length=4)
Pavel Galaton
  • 593
  • 1
  • 6
  • 10
0

PHP doesn't allow for multiple inheritance. You'll need to extend one of them and have the other as a private variable, or something like that.

robbrit
  • 17,560
  • 4
  • 48
  • 68