Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 147 ยท Object-Oriented PHP

Classes, Properties and Methods

Write PHP classes with typed properties, methods, public/protected/private visibility, uninitialized properties, dynamic property rules and clone.

The previous lesson showed what a class is and how new, -> and $this work. Now it's time to write classes the way professional PHP code does: properties with types, methods that guard the object's data, and visibility keywords that decide who may touch what.

You'll also learn three behaviors that surprise people coming from arrays or other languages: typed properties that have no value yet are uninitialized (not null), PHP 8.2 deprecated adding undeclared properties on the fly, and object variables hold handles, so you need clone to copy an object.

Properties

A property is declared inside the class body with a visibility keyword, an optional type, the name, and an optional default value:

PHP
class Article
{
    public string $title = 'Untitled';     // typed, with a default
    public int $views = 0;
    public ?string $summary = null;        // nullable: string or null
    public array $tags = [];
    public bool|int $featured = false;     // union type (PHP 8.0)
    public $legacy;                        // untyped: defaults to null
}

Default values must be constant expressions: literals, constants, arithmetic on them, and arrays of those. You can't call a function or use new in a property default, so public string $created = date('Y-m-d'); fails with "Constant expression contains invalid operations". Values that need computing are set in the constructor.

Typed properties

Typed properties (PHP 7.4) are the modern default. PHP checks every assignment against the declared type. Without strict_types, a value that can be converted safely (like the string "42" for an int) is converted; with declare(strict_types=1); in the file doing the assignment, only an exact type (plus int-to-float widening) is accepted:

PHP Typed properties reject wrong values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The error messages name the class and property, which makes bugs easy to trace. Every type from Type Declarations works on properties (int, ?string, int|float, class names, array, mixed), except void, never and callable.

Uninitialized typed properties

A typed property without a default value starts in a special state: uninitialized. It isn't null; it has no value at all, and reading it throws an Error. This is deliberate: it catches code that forgets to set a required value.

PHP Uninitialized is not null

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the var_dump() output: email and phone are shown as uninitialized(string) and uninitialized(?string), and the property count says (1) because uninitialized properties don't count: only nickname does. isset() returns false for them without throwing, which makes it the safe way to check.

?string doesn't mean "defaults to null". A nullable type only allows null. If you want it to start as null, write the default: public ?string $phone = null;. Untyped properties are the only ones that default to null automatically.

Methods

A method is a function declared inside a class. Everything from Functions and Parameters and Arguments applies: types, defaults, named arguments, variadics. The difference is that a method runs on an object, available as $this.

Good methods do more than shuffle data. They enforce rules, so that the object can never end up in an invalid state:

PHP Methods that protect the data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Because $target is private, the only way to change it is through setTarget(), and setTarget() refuses values out of range. warmer() reuses that check instead of duplicating it. The invalid call throws an exception and the object keeps its last valid value.

Naming methods

  • Actions are verbs: send(), addItem(), warmer().
  • Questions that return bool start with is, has or can: isEmpty(), hasPermission().
  • Accessors are commonly written getTarget()/setTarget(). Many modern codebases drop the get for read-only values (target()), and PHP 8.4 property hooks can replace simple getters and setters entirely.

Returning $this for chaining

A method that changes the object can return $this, which lets callers chain calls. The return type static says "an object of the class this was called on":

PHP
class QueryBuilder
{
    private array $parts = [];

    public function where(string $condition): static
    {
        $this->parts[] = $condition;
        return $this;
    }

    public function toSql(): string
    {
        return 'SELECT * FROM users WHERE ' . implode(' AND ', $this->parts);
    }
}

echo (new QueryBuilder())->where('active = 1')->where('age > 18')->toSql();

That style, called a fluent interface, is common in query builders and configuration objects.

Visibility: public, protected and private

Every property, method and constant has a visibility:

Keyword Accessible from
public Anywhere: outside code, the class itself, child classes
protected The class itself and classes that inherit from it
private Only code inside the class that declares it

The rule of thumb: make properties private by default and expose only the methods outside code needs. That leaves you free to change how the class stores its data without breaking callers. Here's what happens when outside code reaches for private members:

PHP Visibility errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both attempts throw an Error: "Cannot access private property Wallet::$cents" and "Call to private method Wallet::validate() from global scope". Those are not warnings you can ignore; the script stops if they aren't caught.

Visibility is per class, not per object

A detail many developers don't know: private means private to the class, not to one object. A method can read the private properties of another instance of the same class. That's what makes comparison methods easy to write:

PHP Accessing another instance's private data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Visibility keywords also apply to class constants, and PHP 8.4 added asymmetric visibility like public private(set) int $cents, which lets anyone read a property but only the class write it. That's covered in Property Hooks and Asymmetric Visibility.

Dynamic properties are deprecated

In older PHP, assigning to a property that wasn't declared simply created it. That made typos invisible: $user->emial = '...' added a new property instead of failing. PHP 8.2 deprecated this. The assignment still works today, but it prints a deprecation notice, and a future major version is expected to make it an error:

PHP
class User
{
    public string $email = '';
}

$user = new User();
$user->emial = '[email protected]';
// Deprecated: Creation of dynamic property User::$emial is deprecated

Declare every property your class uses. The two exceptions:

  • stdClass, PHP's built-in empty class (what json_decode() and (object) [...] produce), still accepts any property.
  • A class marked with the attribute #[\AllowDynamicProperties] opts back in. Use it only for legacy code you can't fix yet.

Objects are handles: assignment vs clone

As you saw in the introduction, an object variable doesn't contain the object itself. It contains a handle, a small value that identifies the object. Assigning the variable, passing it to a function or returning it copies the handle, and every copy points to the same object.

When you need an independent copy, use the clone operator. It creates a new object with the same property values:

PHP Assignment, clone and shared inner objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output shows the three cases:

  1. $alias = $ana gives two names for one object, so renaming through $alias renames Ana.
  2. clone $ana makes a separate Person, so changing $copy->name leaves Ana alone.
  3. clone is shallow: properties that hold objects are copied as handles, so both people still share one Address. Moving the copy to Porto moves Ana too.

=== on objects is true only when both sides are the very same object. To make clone copy inner objects as well (a deep copy), a class defines a __clone() method; that and == comparison are covered in Comparing, Copying and Serializing Objects. For objects that should never change after creation, see Readonly Properties and Immutable Objects.

Objects aren't passed by reference. It's common to hear "PHP passes objects by reference", but that's not quite right. A function receives a copy of the handle. It can change the object, but assigning a new object to its parameter ($box = new Box();) doesn't affect the caller's variable. Only a real &$box parameter would.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A class has public ?int $age; with no default. What happens on echo $person->age; right after new?

    A nullable type only allows null; it doesn't make null the default. Without "= null" the property is uninitialized and reading it throws an Error.
  2. 2. Which code can read a private property $secret declared in class Vault?

    Private visibility is per class, so a Vault method can read $other->secret on a different Vault. Child classes need protected visibility.
  3. 3. After $b = clone $a; where $a->items is an object, what is true?

    clone is shallow. It creates a new outer object, but properties holding objects copy only the handle unless __clone() deep-copies them.
  4. 4. In PHP 8.2+, what does $user->nmae = "Li"; do when User declares only $name?

    PHP 8.2 deprecated dynamic properties. The property is still created, but you get "Creation of dynamic property User::$nmae is deprecated".

Summary

  • Declare properties with visibility, a type and (usually) a default: private int $views = 0;. Defaults must be constant expressions.
  • Typed properties check every assignment; with strict_types=1, a wrong scalar type throws a TypeError.
  • A typed property without a default is uninitialized: reading it throws an Error, isset() returns false. Nullable types don't default to null unless you write = null.
  • Methods are functions that run on $this. Use them to enforce rules so an object can't become invalid; return $this (type static) for fluent chaining.
  • public is open to everyone, protected to the class and its children, private to the declaring class only (including other instances of it). Prefer private properties.
  • Creating undeclared (dynamic) properties is deprecated since PHP 8.2, except on stdClass or classes marked #[\AllowDynamicProperties].
  • Assigning an object copies its handle. clone makes a new object, but the copy is shallow; === checks whether two variables hold the same object.

Next: Constructors and Destructors