Tools
Log in
English

Learn to codePHP

PHP classes and objects

Based on PHP 8.3constructor promotion · PHP 8.0+

PHP classes with constructor promotion, $this and clone in a coffee order.

In one line

A class is a blueprint that lists values (properties) and the functions that work on them (methods); an object is one copy stamped out of it with new. In PHP, putting an object into another variable does not copy it; both point to the same object.

Why you need it

Ten orders mean thirty loose variables like $drink1, $size1, $shots1, or ten arrays whose keys you type by hand. One wrong key (shot instead of shots) and PHP quietly creates a new slot.

With one CoffeeOrder class that holds the drink, size, shots and the price rule, each order is a single variable. Property names and types live in the class, so a typo turns into an error right away.

Everyday picture

Think of a printed order slip at a cafe. The blank slip (the class) has boxes for drink, size and shots, and each customer gets a filled slip (an object). If two baristas look at a photo of the same slip (two variables), a note written by one shows up for the other; only copying it onto fresh paper (clone) gives a slip you can change separately.

Example code

main.php · 37 lines
<?phpdeclare(strict_types=1); class CoffeeOrder{    public int $shots = 1;     public function __construct(        public string $drink,        public string $size = 'tall',    ) {        echo "New order: {$this->drink}\n";    }     public function addShot(): static    {        $this->shots++;        return $this;    }     public function price(): int    {        $base = $this->size === 'grande' ? 5000 : 4500;        return $base + ($this->shots - 1) * 500;    }} $latte = new CoffeeOrder('latte');$mocha = new CoffeeOrder('mocha', 'grande');$mocha->addShot()->addShot();$same = $latte;$same->shots = 3;$copy = clone $mocha;$copy->size = 'tall';printf("%s %s x%d = %d won\n", $latte->drink, $latte->size, $latte->shots, $latte->price());printf("%s %s x%d = %d won\n", $mocha->drink, $mocha->size, $mocha->shots, $mocha->price());printf("copy: %s x%d = %d won\n", $copy->size, $copy->shots, $copy->price());

When to use it

  • You have many records with the same shape (orders, members, products, posts)
  • You keep typing the same array keys over and over. Those keys are property candidates.
  • You want the values and the rules that change them (pricing, adding shots) in one place

Since PHP 8.2, assigning a property the class never declared (a dynamic property) raises a deprecation notice. Declare every property in the class. The text follows PHP 8.3.

Common mistakes

Leaving out $this->

Inside the method, $ml is just the parameter. PHP never looks up properties on its own, so $ml = $ml assigns the parameter to itself and the object keeps 0. Always reach properties through $this->ml.

Wrong

class Cup{    public int $ml = 0;     public function fill(int $ml): void    {        $ml = $ml;    }} $cup = new Cup();$cup->fill(300);echo $cup->ml, "\n";

When you run it0

Fixed

class Cup{    public int $ml = 0;     public function fill(int $ml): void    {        $this->ml = $ml;    }} $cup = new Cup();$cup->fill(300);echo $cup->ml, "\n";

When you run it300

Calling a method with a dot

Out of JavaScript or Java habit you may write $cup.fill(). In PHP the dot joins strings, so it looks for a plain function named fill() and stops when there is none. Methods and properties use ->.

Wrong

class Cup{    public int $ml = 0;     public function fill(int $ml): void    {        $this->ml = $ml;    }} $cup = new Cup();$cup.fill(300);

When you run itFatal error: Uncaught Error: Call to undefined function fill()

Fixed

class Cup{    public int $ml = 0;     public function fill(int $ml): void    {        $this->ml = $ml;    }} $cup = new Cup();$cup->fill(300);echo $cup->ml, "\n";

When you run it300

A typed property that never gets a value

A typed property such as public string $seat; with no default starts out uninitialized. It is not null either, so reading it throws. Fill it in the constructor or give it a default.

Wrong

class Ticket{    public string $seat;} $t = new Ticket();echo $t->seat, "\n";

When you run itFatal error: Uncaught Error: Typed property Ticket::$seat must not be accessed before initialization

Fixed

class Ticket{    public function __construct(public string $seat)    {    }} $t = new Ticket('A7');echo $t->seat, "\n";

When you run itA7

Check yourself

Question 1

After $y = $x, the shots are changed through $y. What is $x->shots?

$x = new CoffeeOrder('tea');$y = $x;$y->shots = 2;echo $x->shots, "\n";

Show the answer

Answer: 2. 2 Assigning an object copies only the handle. $x and $y point to the same order, so it prints 2. Use clone $x when you need a separate object.

Question 2

What happens when a constructor parameter carries public, as in __construct(public string $drink)?

Show the answer

Answer: 1. It declares the property and assigns the argument in one go That is constructor promotion (PHP 8.0+). It replaces the property declaration, the parameter and $this->drink = $drink with one line. private, protected and readonly work in the same spot.

Questions people ask

What is $this?

The object written before the arrow when the method was called. Inside a method, always reach properties through $this->name.

Does assigning an object to another variable copy it?

No. You get a second handle to the same object. Use clone when you need a separate copy.

Since when can I use constructor promotion?

Since PHP 8.0. Put public, private or readonly before a constructor parameter to declare and assign the property in one go.