Menu

PHP Class and Object: Properties, Methods and $this

A PHP class is a blueprint declared with class Name { }, and new Name() creates an object from it. Learn properties, methods, $this, public/private/protected, typed and readonly properties, __toString, and why assigning an object does not copy it.

This page includes runnable editors - edit, run, and see output instantly.

A PHP class is declared with class Name { ... } and holds properties (variables) and methods (functions). new Name() creates an object from it, and -> reads a property or calls a method: $user->name, $user->greet().

The class is the blueprint, the object is one thing built from it. You can create as many objects from one class as you need, and each has its own property values.

Properties and methods

A property is declared with a visibility keyword, an optional type and an optional default value. A method is a function inside the class. Inside a method, $this is the object the method was called on, so $this->balance reads that object's balance.

Each object keeps its own $balance: depositing into $a does not touch $b. Setting properties one by one after new gets tedious; a constructor takes the starting values as arguments instead.

public, private and protected

Visibility controls who can touch a property or call a method:

KeywordAccessible from
publicanywhere
protectedthe class itself and classes that extend it
privateonly the class that declares it

Making a property private and exposing methods is how a class protects its own rules. Here the balance can only change through deposit() and withdraw(), which refuse bad amounts:

Reading the private property from outside the class is not a warning, it is an Error:

Typed properties and uninitialized values

A typed property without a default value starts out uninitialized, which is different from null. Reading it before anything is assigned throws an Error. Either give it a default, assign it in the constructor, or make it nullable with ?Type and = null.

Types are enforced on assignment. With the default (non-strict) mode, $p->stock = '7' converts the numeric string to 7, while $p->stock = 'many' throws a TypeError.

readonly properties

A readonly property (PHP 8.1) can be written once, from inside the class, and then never again. It is the usual way to build value objects such as money amounts or IDs. PHP 8.2 added readonly class, which makes every property readonly.

A readonly property must have a type, and it cannot have a default value. If you need a changed copy, create a new object (new Order('B-2002')) instead of editing the old one.

echo $object only works when the class defines __toString(). The method returns the string PHP should use whenever the object is treated as text: in echo, in string concatenation, in "{$object}".

Without __toString, echo $object throws an Error ("Object of class Money could not be converted to string"). For debugging, print_r() and var_dump() work on any object and show private properties too; see var_dump and print_r.

Assigning an object does not copy it

This is the mistake that bites most people coming from arrays. Assigning an array copies it. Assigning an object copies only the handle: both variables then point to the same object.

clone makes a shallow copy: if a property holds another object, both copies still share that inner object. === is true only for the same object, while == compares the property values of two objects of the same class. Passing an object to a function works the same way as assignment, so a function can change the object it receives.

Frequently Asked Questions

How do I create an object from a class in PHP?

Use new with the class name: $user = new User();. If the class has a constructor, pass its arguments in the parentheses, as in new User('Ada'). You then call methods and read properties with the arrow operator: $user->name, $user->greet().

What does $this mean in PHP?

$this is the object the current method was called on. Inside $ada->greet(), $this is $ada, so $this->name reads Ada's name. It only exists inside non-static methods.

What is the difference between public, private and protected in PHP?

public members can be used from anywhere, private members only from inside the class that declares them, and protected members from that class and its child classes. Reading a private property from outside throws an Error: Cannot access private property.

Are objects passed by reference in PHP?

A variable holds a handle to the object, not the object itself. $b = $a; copies the handle, so both variables point to the same object and a change through $b shows up in $a. Use $b = clone $a; to get an independent copy.

What is a readonly property in PHP?

A property declared public readonly string $id; (PHP 8.1+) can be set once, from inside the class, and never changed afterwards. Writing to it a second time throws an Error: Cannot modify readonly property.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED