Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 147 ยท Object-Oriented PHP

Object-Oriented Programming in PHP

Learn why PHP uses objects, how a class differs from an object, and how to write a first class with properties, methods, new and $this.

So far you've stored data in variables and arrays and processed it with functions. That works well for small scripts, but as a program grows, the data and the functions that work on it drift apart. A $cart array gets passed to addItem(), removeItem(), cartTotal() and a dozen other functions, any of which can put anything into it. Nothing stops a typo like $cart['itmes'], and nothing tells a reader which functions belong to carts.

Object-oriented programming (OOP) bundles the two together. A class describes a kind of thing: what data it holds and what it can do. An object is one concrete thing built from that description. Almost all modern PHP is written this way: Laravel, Symfony, WordPress plugins, Composer packages and PHP's own DateTimeImmutable, PDO and exception classes are all classes.

This lesson introduces the core ideas with a first class, the new keyword and the special $this variable. The rest of the chapter builds on it, starting with Classes, Properties and Methods and Constructors and Destructors.

From arrays and functions to objects

Here's a small program written without objects. A bank account is an associative array, and two functions change it:

PHP An account as an array

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.

It works, but notice the problems:

  • The shape of an "account" exists only in the programmer's head. Any array can be passed to deposit().
  • Any code anywhere can set the balance to nonsense, so the rule "a balance is changed only by deposits and withdrawals" can't be enforced.
  • A typo creates a new key instead of an error.
  • Nothing groups deposit() and describe() together; in a large project they could live in different files.

Objects fix all four. Here's the same idea as a class:

PHP The same account as a class

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 data (owner, balance) and the behavior (deposit(), describe()) now live in one place, and every BankAccount has exactly the same shape. Later lessons add the protection: visibility hides balance from outside code, and constructors make sure every account starts valid.

Classes and objects

The difference between the two words is the single most important idea in OOP:

  • A class is a blueprint. class BankAccount { ... } describes what every bank account has and does. Declaring a class creates no account at all.
  • An object (also called an instance) is one thing built from the blueprint. Each new BankAccount() creates a separate object with its own data.

Think of a class as a cookie cutter and objects as cookies. One cutter, many cookies, and biting one cookie doesn't change the others.

The vocabulary for what goes inside a class:

Term Meaning In the example
Property A variable that belongs to an object $owner, $balance
Method A function that belongs to a class deposit(), describe()
Instance An object made from a class $account
Member Any property, method or constant of a class all of the above

Declaring a class

A class declaration starts with the keyword class, then the name, then a body in braces:

PHP
class Product
{
    public string $name = '';
    public int $priceInCents = 0;

    public function label(): string
    {
        return $this->name . ' - ' . number_format($this->priceInCents / 100, 2);
    }
}

Conventions that nearly all PHP code follows (they come from the PSR-12 and PER coding style):

  • Class names use PascalCase: Product, BankAccount, HttpClient.
  • Methods and properties use camelCase: priceInCents, label().
  • The opening brace of a class or method goes on its own line; one class per file in real projects, with the file named after the class (Product.php). That convention lets autoloading find classes automatically.

Class names are case-insensitive in PHP (new product() works), but always write them exactly as declared.

The keyword public before each member is its visibility: public members can be used from anywhere. The types (string, int) are typed properties, which make PHP reject a wrong value. Both get a full treatment in the next lesson.

Creating objects with new

The new operator builds an object from a class. Then the object operator -> reaches into it: $object->property reads or writes a property (note: no $ before the property name), and $object->method() calls a method.

PHP Several independent 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.

Each object has its own copy of every property, so lowering the pen's price doesn't touch the lamp. The instanceof operator checks whether a value is an object of a given class, and get_class() returns an object's class name.

Parentheses after new. When a class's constructor takes no arguments, new Product and new Product() mean the same thing. This tutorial always writes the parentheses. PHP 8.4 also lets you call a method directly on a new object without wrapping it in extra parentheses, as in new Product()->label(); you'll see that in Constructors and Destructors.

$this: the current object

Inside a method, $this is a variable that refers to the object the method was called on. When you write $pen->label(), $this inside label() is $pen; for $lamp->label(), it's $lamp. That's how one method definition serves every object.

PHP $this changes with the object

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.

Two things beginners often get wrong:

  • Inside a method, properties need $this->. Writing $count++ instead of $this->count++ creates a local variable $count that disappears when the method returns. PHP doesn't automatically look up properties the way Java or C++ do.
  • Methods calling methods also need $this->. increment() on its own would look for a global function named increment, and fail.

In string interpolation, "$this->name" works for a simple property; the {$this->name} form is clearer and also handles method calls and array access, as covered in Strings.

Looking inside objects

The debugging tools from Output: echo, print, printf work on objects too. var_dump() gives the most detail:

PHP var_dump and print_r on 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.

Read the first line of var_dump() output like this:

TEXT
object(Book)#1 (4) {
  • object(Book): it's an object of class Book.
  • #1: the object id, a number PHP gives each object while it's alive. The second book is #2. Ids are useful when debugging to tell whether two variables hold the same object; an id can be reused after an object is destroyed.
  • (4): the number of properties.

Below that, each property is listed with its type and value, exactly like an array element. print_r() gives a shorter view with Book Object as the header. Neither is meant for users; they're for you while debugging.

Echoing an object is an error. echo $book; throws an Error: "Object of class Book could not be converted to string". To give a class a string form, add a __toString() method, covered in Magic Methods.

Objects behave like handles

One more behavior is worth knowing from day one, because it differs from arrays. Assigning an array copies it; assigning an object does not copy the object. Both variables then refer to the same object:

PHP Objects are shared, arrays are copied

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 array stays 1, but $boxA->value shows 2 and then both boxes read 0 after the function call. A variable holding an object really holds a handle (an id pointing to the object), and copying the variable copies the handle. To get an independent copy you use clone, which the next lesson explains along with the details of this model.

Why bother with OOP?

The benefits grow with the size of a program:

  • Encapsulation. An object guards its own data. With private properties and methods that check their input, a BankAccount can guarantee its balance never goes negative.
  • A clear vocabulary. $invoice->send(), $user->isAdmin() and $cart->total() read like the problem domain. The class name tells you where the code lives.
  • Types you can rely on. A function declared as function ship(Order $order) accepts only Order objects, so it never receives a half-built array. See Type Declarations.
  • Reuse and flexibility. Inheritance, interfaces and traits let different classes share behavior or be swapped for each other.
  • The ecosystem. Frameworks, libraries and PHP's own extensions are object-oriented. Reading their code requires knowing classes.

OOP isn't a rule that every line must live in a class. Small scripts and pure helper functions are fine as plain functions. But once data has rules ("an email must be valid", "a balance can't go negative"), a class is the natural place to keep them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement best describes the relationship between a class and an object?

    Declaring a class creates no data. Every new ClassName() creates an independent object from that description.
  2. 2. Inside a method, public function grow(): void { $size++; } is meant to increase the property $size. What happens?

    PHP needs $this->size to reach the property. A bare $size is a new local variable (and here it also triggers an "Undefined variable" warning).
  3. 3. Given $a = new Box(); $a->value = 1; $b = $a; $b->value = 5;, what is $a->value?

    Assigning an object copies the handle, not the object. $a and $b refer to the same Box.
  4. 4. In var_dump() output, what does #2 in object(Book)#2 (4) mean?

    The number after # is the object id. The count of properties is the number in parentheses: (4).

Summary

  • A class declares the properties (data) and methods (functions) that its objects have. An object, or instance, is created with new ClassName().
  • Each object has its own property values; changing one object doesn't affect another.
  • The object operator -> reads and writes properties ($book->title, no $ on the property) and calls methods ($book->label()).
  • Inside a method, $this is the object the method was called on. Use $this->property and $this->method(); a bare $name is a local variable.
  • var_dump() shows object(Class)#id (property count) plus every property; print_r() gives a shorter view. Echoing an object without __toString() is an error.
  • Assigning or passing an object shares the same object (a handle). Arrays are copied.
  • Classes use PascalCase names, members use camelCase, and real projects keep one class per file.

Next: Classes, Properties and Methods