I have a class PlaylistTrack that I want to extend class Song.
When I construct Song I pass in an array of data like artist, title etc.
When I construct PlaylistTrack I want it to have all song’s methods as well as the new methods it introduces.
But I also want to pass in the specific song in its constructor.
So I’m doing this:
class Song {
function __construct( $song_data ) {
$this->_data = $song_data;
// etc
}
}
And then this. Don’t shoot me!
class PlaylistTrack extends Song {
function __construct( $song ) {
// call the song's constructor again in the context of this class
// to give access to its methods.
parent::__construct( $song->_data );
// other PlaylistTrack-specific material to go here
}
}
This feels peculiar, to say the least. Is it ok? Is there an alternative?
The constructor is inherited automatically when extending a class. If you aren’t planning to add functionality to your existing constructor, you don’t need to polymorph it.
If you do want to add functionality to it, what you’ve done is perfectly fine.