How to play a Song on Guitar using PHP (part 3)
Let’s improve the previous script that we have wrote in the previous post.
At the previous script we modify our Classes to support the double equality ==
operator. If we want to check whether two Songs
are the same, we have to remember or check or keep in the documentation whether we have impement the support of double equality operator. So what if instead of
$song == $anotherSong
we compare with the a method called isSameWith
?
$song->isSameWith($anotherSong)
- The code is saying what is doing
- We hide the details of the implementation
- We can easily change the specifications of the definition of
isSameWith
inside the object, without affecting other objects that is using it.
class Note
{
/** hidden code */
public function isSameWith(Note $anotherNote): bool
{
return $this == $anotherNote;
}
}
class Song
{
/** hidden code */
public function isSameWith(Song $anotherSong): bool
{
return $this == $anotherSong;
}
}
function printWhetherSongsAreEqual(Song $song, Song $anotherSong)
{
if ($song->isSameWith($anotherSong)) {
echo 'The two songs are the same.' . PHP_EOL;
} else {
echo 'The two songs are NOT the same.' . PHP_EOL;
}
}
When we run the script we will see the following.
[savvas@localhost play_guitar_with_php]$ php play_guitar_second.php
Is $song equal with $anotherSong?
The two songs are the same.
Is $song equal with $beethovenFifthSympony?
The two songs are NOT the same.
That’s all for today.
Copy the Script 🔓 and Play with it ⛹.
Be Creative 🎨 and Send me an Email 📧.