An introduction to Object Oriented Programming with PHP

With PHP we can play a Song using a Guitar! For example with the following script.

<?php

$guitar->play($song);

In order to do that, we need to create two new Objects,

  • A Guitar and
  • A Song
<?php

$guitar = new Guitar();
$song = new Song();
$guitar->play($song);

The PHP does not know how to create those Objects, since they are not familiar to her. In order to instantiate them, we have to define their Classes.

<?php

class Guitar
{
}

class Song
{
}

Also the Guitar needs a method called play with a Song as parameter.

<?php

class Guitar
{
  
  function play(Song $song)
  {
	/* I am not able to play the $song yet :( */
  }
}

Our Guitar is not able to play the Song yet 😞

We have to implement the method play and the song needs some notes!

Let’s construct a song first. We’ll use the solfège naming convention Do, Re, Mi, Fa, Sol, La, Si for notes. A simple melody is the Beethoven 5th Symphony, that is sounds like that:

Sol, Sol, Sol, Mi, Fa, Fa, Fa, Re

We will use the structure of Array to represent the 5th Symphony and by the instantiation of a Song we parse as parameter the Array of notes.

$notes = ['Sol', 'Sol', 'Sol', 'Mi', 'Fa', 'Fa', 'Fa', 'Re'];
$guitar = new Guitar();
$song = new Song($notes);
$guitar->play($song);

We modify the Song class in order to accept the song notes as parameter on its construction. We can do this by implementing the method __construct

<?php

class Song 
{
  public $notes = [];
  
  function __construct(array $notes)
  {
	$this->notes = $notes;
  }

}

Note that $notes is a property of the Class Song. The variable $this is refering to the object.

After we have instantiated the song we will be able to implement the play method.

<?php

class Guitar
{  

  function play(Song $song)
  {
	foreach($song->notes as $note) {
		echo '🎵' . $note . PHP_EOL;
		sleep(1);
	}
  }  

}

Here is the script.

Copy the Script 🔓 and Play with it ⛹.

Be Creative 🎨 and Send me an Email 📧.