Lesson 20 of 100
Classes12 min5 checksPHP 8.5

Classes: Create and Use an Object

Learn to define a PHP class, store values in properties through a constructor, and read them from instance methods with $this.

01 · THE IDEAREAD → TRY → LEARN

Why classes?

A function takes values in and gives a value back. A class lets you keep related values and the functions that use them in one unit. The values are called properties. The functions are called methods. One instance of a class is an object.

A class definition starts with the keyword class, then a name, then a pair of curly braces. Inside the braces you declare properties and methods. The class is only a blueprint. Nothing exists until you create an object from it with new.

A first class

The example below defines Greeter. It has one property, name, and two methods. The method called __construct is the constructor. PHP runs it automatically every time you write new Greeter(...), and the arguments in the parentheses are passed to it.

Example
<?php
class Greeter
{
    public string $name;

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

    public function greet(): string
    {
        return "Hello, " . $this->name . "!";
    }
}

$greeter = new Greeter("Ada");
echo $greeter->greet(), PHP_EOL;
Output
Hello, Ada!

Two things to notice. First, the constructor copies its parameter into the property with $this->name = $name;. The parameter disappears when the constructor ends, but the property stays on the object. Second, greet() reads that property with $this->name. Inside a method that is called on an object, $this means "the object this method was called on". You use -> to reach a property or call a method.

Each object has its own state

You can create as many objects from one class as you like. Each one keeps its own property values, so changing one does not affect the others. Constructor parameters can have defaults, just like function parameters.

Example
<?php
class Counter
{
    private int $count;

    public function __construct(int $start = 0)
    {
        $this->count = $start;
    }

    public function increment(): int
    {
        $this->count++;
        return $this->count;
    }
}

$a = new Counter();
$b = new Counter(10);
echo $a->increment(), PHP_EOL;
echo $a->increment(), PHP_EOL;
echo $b->increment(), PHP_EOL;
Output
1
2
11

The count property is private, so code outside the class cannot touch it directly. Only the methods of Counter can read or change it. That is why the class offers increment(). Use public for members that outside code is meant to use, and private for internal details.

Objects are handled by identity

When you assign an object to another variable, PHP does not copy the object. Both variables point to the same instance. The same is true when you pass an object to a function. To get an independent copy you must use clone.

Example
<?php
class Box
{
    public function __construct(public string $label)
    {
    }
}

$first = new Box("draft");
$second = $first;
$second->label = "final";
echo $first->label, PHP_EOL;

$copy = clone $first;
$copy->label = "copy";
echo $first->label, PHP_EOL;
echo $copy->label, PHP_EOL;
Output
final
final
copy

Here the constructor declares public string $label right in its parameter list. That shorthand declares the property and assigns the argument to it in one step. It does the same job as the longer form in Greeter.

Common mistakes

  • Writing name instead of $this->name inside a method. A bare $name is just a local variable and is not the property.
  • Writing $this->$name. The property is accessed as $this->name, with no second dollar sign.
  • Forgetting new. A class name on its own does not give you an object.
  • Expecting $second = $first to copy an object. It shares the instance.
  • Calling an instance method as if it were static. Methods that use $this need an object.

Exercise contract

Write the function describeBook(string $title, int $pages): string. Inside the file, complete the class Book:

  1. The constructor receives a title and a page count and stores both in properties.
  2. A method summary() reads those properties and returns text in the form Title (N pages).
  3. When the page count is exactly 1, the word is singular: Title (1 page).
  4. describeBook() creates a Book with new and returns the result of summary().

For example, describeBook("PHP Basics", 120) returns PHP Basics (120 pages). Zero pages is plural, so it gives (0 pages). The tests check the returned string, so do not echo it.

Recap

A class groups properties and methods. new builds an object and runs the constructor, which usually stores its arguments in properties via $this->. Instance methods read that stored state through $this. Assigning an object shares it, and clone makes a separate copy.

Before you start

Functions · Strings

You’ll practice
  • Store an object property in a constructor
  • Read a property from an instance method
Your task

Make describeBook() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.