Evolution Note: This mad-scientist experiment was written in March 2019 and reviewed in July 2026. While my day job now centers around designing production-grade AI systems and robust automation backends, I will always have a soft spot for pushing technologies to their absolute limits—and using them in ways they were never intended to be used. If you are looking for my current technical architecture and consulting services, feel free to visit my homepage or book an architecture review session.

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 📧.