PHP Trail
Workflows

PHP OOP tutorial: your first class, built step by step

03
Start a class

Practice classes with a product class

A PHP OOP tutorial makes more sense when the class is yours, so the scenario here is a Product class with a name, a price and a method that returns a label. The PHP learning curve gets steeper when classes appear, so one file and small steps keep it manageable. Run it after every change.

01

Open an empty folder

Create a folder for the project, choose it as the chat's working folder and select Ask first before you type a prompt.

02

Describe the class

Ask for Product.php with a private name and price, a constructor and a method that returns a label.

03

Read the card, then accept

Open the card and read the file or the diff. Ask first pauses before anything is saved, so you can reject it.

04

Run it and compare

Shell runs php Product.php and prints the real output; compare the printed labels with what you expected.

A small script to read first

totals.php
<?php
// Add up the minutes in a small daily practice plan.
declare(strict_types=1);

$minutes = ['read' => 20, 'type' => 25, 'review' => 10];

foreach ($minutes as $task => $amount) {
    echo "$task: $amount minutes\n";
}

echo 'Total: ' . array_sum($minutes) . " minutes\n";

totals.php is a separate warm-up. It stores three times in an associative array, prints each with foreach and adds them with array_sum, so read it before you write the class.

A PHP web development tutorial: a class method and a form

Add a method and read the diff

Once Product.php runs, ask for a method that applies a discount to the price and returns the new value as a float. edit_file changes the existing class and shows the edit as a diff, so you see exactly which lines were added before you accept them in Ask first mode. Keep declare(strict_types=1) at the top and give the method a return type, because strict types make a wrong argument fail loudly instead of being converted. In-depth resources on PHP basics, such as the PHP manual, explain return types and strict types in full. Shell then runs php -l Product.php and php Product.php. The result is real. Print the old and the new price yourself and check the arithmetic by hand before you trust the method.

Answer a form on the server

If you know HTML and CSS and wonder whether to learn PHP or JavaScript after them, this session shows the server-side half: PHP runs on the server, while JavaScript is usually met in the browser. Ask for a contact form page that only displays a thank-you message with the sender's name escaped through htmlspecialchars. write_file saves it, Shell runs php -l on it, and you start php -S localhost:8000 in your own terminal for local testing only. Open the page. Submit a name. Read each diff in Ask first mode, and test the page yourself before you accept the next change.

PHP Trail for Windows

Build your first class

Download PHP Trail ↗