Skip to content

PHP Tutorial Object-Oriented PHP

Properties

Lesson 200 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Properties are the variables that belong to an object. They hold its data.

index.php
PHP
<?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}";
Output
OUTPUT
Notebook costs 80.5

Typed properties

Since PHP 7.4, properties can have types, just like function parameters. PHP then checks every assignment.

index.php
PHP
<?php
class Product
{
    public int $stock = 0;
}

$p = new Product();

try {
    $p->stock = "many";
} catch (TypeError $e) {
    echo $e->getMessage();
}
Output
OUTPUT
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.

index.php
PHP
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.

index.php
PHP
<?php
class User
{
    public string $name = "";
    public ?string $phone = null;
}

$u = new User();

var_dump($u->phone);
Output
OUTPUT
NULL

Uninitialized typed properties

A typed property without a default has no value at all until you set it. Reading it throws an error.

index.php
PHP
<?php
class User
{
    public string $name;
}

$u = new User();

try {
    echo $u->name;
} catch (Error $e) {
    echo $e->getMessage();
}
Output
OUTPUT
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.

index.php
PHP
<?php
class Order
{
    public function __construct(public readonly int $id) {}
}

$order = new Order(1042);

try {
    $order->id = 7;
} catch (Error $e) {
    echo $e->getMessage();
}
Output
OUTPUT
Cannot modify readonly property Order::$id

Listing properties

index.php
PHP
<?php
class Point
{
    public int $x = 1;
    public int $y = 2;
}

print_r(get_object_vars(new Point()));
Output
OUTPUT
Array
(
    [x] => 1
    [y] => 2
)

Check if a property is set

index.php
PHP
<?php
class Box
{
    public ?int $size = null;
}

$box = new Box();

var_dump(isset($box->size));
var_dump(property_exists($box, "size"));
Output
OUTPUT
bool(false)
bool(true)
info
Public properties are easy but open
Anyone can change a public property to anything of the right type. The lesson on visibility shows how to protect data.