我有一个 PlaylistTrack 类,我想扩展 Song 类。
当我构造歌曲时,我会传入一系列数据,例如艺术家、标题等。
当我构建 PlaylistTrack 时,我希望它具有所有歌曲的方法以及它引入的新方法。
但我也想在其构造函数中传递特定的歌曲。
所以我正在这样做:
class Song {
function __construct( $song_data ) {
$this->_data = $song_data;
// etc
}
}
然后是这个。别开枪打我!
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
}
}
至少可以说,这感觉很奇怪。可以吗?有替代方案吗?
最佳答案
扩展类时会自动继承构造函数。如果您不打算向现有构造函数添加功能,则无需对其进行多态处理。
如果您确实想为其添加功能,那么您所做的就完全没问题。
关于php - 在扩展类中“重建”父对象 - 这是可怕的代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11122566/