A Moderately Short PHP Tutorial

Classes and Objects

PHP supports class-based object oriented programming, heavily influenced by Java and similar languages. This is different to the prototype based OO in JavaScript.

In the sort of PHP code I write almost 100% of the code in a project is in classes - some classes are used to make objects, and others may just be convenient wrappers around groups of functions.

In PHP every object is an instance of a class, so you have to have a class before you can have an object. Let's write a class to let us make Planet objects. How to write classes changed a bit in PHP 7.4. Enter the following in a file called Planet.php:

<?php declare(strict_types=1);

namespace AModeratelyShortPhpTutorial;

final class Planet
{
    private string $name;

    private float $populationSize;

    public function __construct(string $name, float $populationSize)
    {
        $this->name = $name;
        $this->populationSize = $populationSize;
    }

   public function getName(): string
   {
       return $this->name;
   }

   public function getPopulationSize(): float
   {
       return $this->populationSize;
   }
}

Older PHP Versions

name and populationSize are the properties of the class, and they have string and float types respectively. Before 7.4 PHP didn't allow us to specify types for properties. We still want to know what types of values we intend to put in the properties, so we use a DocBlock instead. If you don't have 7.4 yet, change the property declarations to:

    /**
     * @var string
     */
    private $name;

    /**
     * @var float
     */
    private $populationSize;

These DocBlocks are ignored by the PHP engine, but they are very useful for us, and many tools and IDEs will read them. The code inside the docblock is written in the PHPDoc language.

Running the code

Run php Planet.php. You should see no output - a class by itself doesn't do anything. We will write code to use this class on the next page.

What's in the class

Let's read through the class from top to bottom.

If you know JavaScript, you can think of a class with public and private parts as serving a similar purpose to a JavaScript module that exports some but not all of its symbols.