I have a class whose purpose is to display a comment. I'd like to be able to instantiate it by passing a Comment
object if I happen to have it available, or just the values if that's what I have available at the time. Unfortunately PHP doesn't allow overloaded constructors, so here's the workaround I came up with.
class CommentPanel extends Panel {
//Private Constructor, called only from MakeFrom methods
private function CommentPanel($text, $userName, $timestamp) {
parent::Panel(0, $top, System::Auto, System::Auto);
// Render comment
}
public static function MakeFromObject(Comment $comment) {
return new CommentPanel($comment->text, $comment->User->nickname, $comment->last_updated_ts);
}
public static function MakeFromValues($text, $userName, $timestamp) {
return new CommentPanel($text, $userName, $timestamp);
}
}
So here's the two methods for instantiating a CommentPanel
:
$cp = CommentPanel::MakeFromObject($comment);
// or...
$cp = CommentPanel::MakeFromValues($text, $user, $last_updated_ts);
// but not
$cp = new CommentPanel(); //Runtime error
I'm moderately satisfied, although it's not near as intuitive as an overloaded constructor. Any thoughts on improving this?