I wrote these two classes that simple encrypt and decrypt strings:
Encode.php
class Encode {
protected funcion do_encode($string) { .. }
}
Decode.php
class Decode {
protected funcion do_decode($string) { .. }
}
What I would like to do is:
Encrypt.php
class Encrypt extends Encode, Decode {
protected $stuff_for_parents;
function __construct($configs) {
$this->stuff_for_parents = $configs['SomeConf'];
}
public function encode($string) { $this->do_encode($string); }
public function decode($string) { $this->do_decode($string); }
}
But we cannot include more than one class, so: fail.
Now my questions are:
- Is it a design problem? Cause this scenario doesn’t look weird to me, does it?
- Is there another way to have one object that uses both the functions in the different classes? Sort of
$encrypt->encode($str);$encrypt->decode($str);
If you want Encode and Decode to be separate classes, you can create instances of them within Encrypt. For example:
In that example Encode and Decode must be concrete classes. But you might want to consider using interfaces instead. Interfaces are useful if you think you might need to use different types of Encode and Decode objects, in different situations. For example, maybe you have a TripleDESEncode class and a BlowfishEncode class. They can both implement a common interface, like this:
In that case, you may want to create the particular instances you want to use first, and then pass them into the constructor of Encrypt. This is called dependency injection: