I agree that constants are the better approach (in my opinion). However, I think a slightly different approach to what you seem to be doing would be the following:
PHP Code:
interface IDocument
{
function getContents();
}
class TextDocument : IDocument
{
public function getContents()
{
}
}
class PdfDocument : IDocument
{
public function getContents()
{
}
}
class HtmlDocument : IDocument
{
public function getContents()
{
}
}
// class 1
class MyDocument {
public function getContents(IDocument $format) {
return $format->getContents();
}
}
// usage:
$document->getContents(new HtmlExtension());
Why? Because 1) it requires you to only provide something that is implemented (meaning you can't pass an integer to replace a constant, or a string for that matter) nor can you pass a misspelling and 2) It allows you to use DI to separate logic that may be different for each extension, thus making your MyDocument class less crowded.

Originally Posted by
Lemon Juice
Interesting, I've never thought of it this way. And I think I can see why this would be logical. But we would need to always define interfaces - some argue that we should define an interface for every class.
I'm a HUGE fan of interfaces, but you need to use them where it makes sense. Most base classes should have an interface, beyond that, when you extend a class you usually lose the purpose of the interface at that level. So in my prior example, I created an IDocument interface that TextDocument, HtrmlDocument, and PdfDocument all utilize. If I ever needed a base class (Document) to provide something common among the three classes then I'd only have Document associated to the interface and TextDocument, HtmlDocument, and PdfDocument would inherit Document (which allows them to utilize the Interface too, I wouldn't build an Interface for each of them unless there was a specific implementation I needed it to conform to) -- I hope that makes sense.
Edit:
I like how oddz kept his named Document, so I've updated my example to be similar
Bookmarks