PHP Tutorial · Object-Oriented PHP · Lesson 29 of 38
PHP Classes and Objects
Define classes with properties and methods, and create objects.
A class and its objects
A class defines properties (data) and methods (behaviour). new creates an object; -> accesses its members; $this refers to the current object:
<?php
class Product
{
public string $name;
private float $price;
public function setPrice(float $price): void
{
if ($price < 0) {
throw new InvalidArgumentException("Price can't be negative");
}
$this->price = $price;
}
public function label(): string
{
return sprintf("%s — $%.2f", $this->name, $this->price);
}
}
$mug = new Product();
$mug->name = "Mug";
$mug->setPrice(9.5);
echo $mug->label(), "\n";
Output
Mug — $9.50
Visibility
public— accessible everywhere.protected— inside the class and its children.private— inside the class only.
Keep properties private and expose behaviour through methods, so the object controls its own rules.
Readonly properties
A readonly property can be set once (in the constructor) and never changed — great for value objects:
<?php
final class Money
{
public function __construct(
public readonly int $cents,
public readonly string $currency = "USD",
) {}
public function add(Money $other): Money
{
return new Money($this->cents + $other->cents, $this->currency);
}
}
$total = (new Money(1999))->add(new Money(501));
echo $total->cents, " ", $total->currency, "\n";
try {
$total->cents = 0;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
Output
2500 USD Cannot modify readonly property Money::$cents
Test yourself
Which operator accesses a property or method on an object?
.->::=>
Show answer
Answer: ->