在扩展类中“重建”父对象 - 这是可怕的代码


'reconstructing' parent object in extending class - is this horrible code?

我有一个类播放列表跟踪,我想扩展类歌曲。

当我构建歌曲时,我会传入一系列数据,如艺术家、标题等。

当我构建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
     }
}

至少可以说,这感觉很奇怪。可以吗?有没有其他选择?

扩展类时会自动继承构造函数。如果不打算向现有构造函数添加功能,则无需对其进行多态处理。

如果您确实想为其添加功能,那么您所做的一切都很好。