Evolution Note: This experiment was written in March 2019 and reviewed in October 2026. While my day job focuses on distributed backends and automation systems, applying object-oriented modeling to unconventional problems like audio synthesis remains a fun demonstration of software design basics. For current technical publications, visit the homepage.

Object-oriented programming helps developers translate real-world mental models into clean software structures. To explore basic classes and methods, we can model a virtual Guitar that plays a Song directly in PHP.

Our ideal script syntax looks like this:

<?php

$guitar->play($song);

Representing Music with Objects

To make that call work, we need two separate objects: a Guitar instrument and a Song that holds musical data:

<?php

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

PHP requires class blueprints before it can instantiate these objects. We start by declaring empty classes:

<?php

class Guitar
{
}

class Song
{
}

Defining the Guitar and Song Classes

Next, the Guitar needs a play() method that accepts a Song instance as a parameter:

<?php

class Guitar
{
    public function play(Song $song)
    {
        // Waiting for playable notes
    }
}

To give the song actual melody data, we use the standard solfรจge scale (Do, Re, Mi, Fa, Sol, La, Si). A recognizable melody is the opening motif of Beethovenโ€™s 5th Symphony:

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

We represent these notes as an array and pass them into the Song upon creation:

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

Passing Notes to the Constructor

We update the Song class to store the melody notes in an internal property via its constructor:

<?php

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

The $notes array becomes an instance property, and $this->notes refers to the specific song being constructed.

Playing Notes in the Terminal Loop

With the notes accessible on the Song object, we implement the play() method on the Guitar:

<?php

class Guitar
{  
    public function play(Song $song)
    {
        foreach ($song->notes as $note) {
            echo '๐ŸŽต ' . $note . PHP_EOL;
            sleep(1);
        }
    }  
}

When you execute this script in a local terminal window, the virtual guitar iterates through the note array, outputting each musical pitch rhythmically once per second.

You can inspect the full standalone snippet on GitLab Snippets. If you experiment with creative terminal simulations, feel free to share your thoughts via Email.