Properties are the variables that belong to an object. They hold its data.
<?php
class Product
{
public string $name = "Unnamed";
public float $price = 0.0;
public int $stock = 0;
}
$p = new Product();
$p->name = "Notebook";
$p->price = 80.5;
echo "{$p->name} costs {$p->price}";
Notebook costs 80.5
Typed properties
Since PHP 7.4, properties can have types, just like function parameters. PHP then checks every assignment.
<?php
class Product
{
public int $stock = 0;
}
$p = new Product();
try {
$p->stock = "many";
} catch (TypeError $e) {
echo $e->getMessage();
}
Cannot assign string to property Product::$stock of type int
Always type your properties. It catches mistakes the moment they happen.
Default values
A default must be a constant value (number, string, array, null, true/false, a constant). You cannot call a function in a default.
public array $tags = [];
public string $status = "draft";
public ?string $note = null;
// public int $created = time(); // not allowed
Nullable properties
Use ? when a property may legitimately be null.
<?php
class User
{
public string $name = "";
public ?string $phone = null;
}
$u = new User();
var_dump($u->phone);
NULL
Uninitialized typed properties
A typed property without a default has no value at all until you set it. Reading it throws an error.
<?php
class User
{
public string $name;
}
$u = new User();
try {
echo $u->name;
} catch (Error $e) {
echo $e->getMessage();
}
Typed property User::$name must not be accessed before initialization
The usual fix is to set required properties in the constructor, so an object is never half-built. See Constructors.
Readonly properties (PHP 8.1+)
A readonly property can be set once, and then never changed. It is great for values that must not change.
<?php
class Order
{
public function __construct(public readonly int $id) {}
}
$order = new Order(1042);
try {
$order->id = 7;
} catch (Error $e) {
echo $e->getMessage();
}
Cannot modify readonly property Order::$id
Listing properties
<?php
class Point
{
public int $x = 1;
public int $y = 2;
}
print_r(get_object_vars(new Point()));
Array
(
[x] => 1
[y] => 2
)
Check if a property is set
<?php
class Box
{
public ?int $size = null;
}
$box = new Box();
var_dump(isset($box->size));
var_dump(property_exists($box, "size"));
bool(false)
bool(true)