Skip to content

PHP Tutorial Object-Oriented PHP

Classes

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

A class is a blueprint. It describes what an object will have (properties) and what it can do (methods). The class itself is not the thing. It is the plan for making things.

index.php
PHP
<?php
class Book
{
    public string $title = "Untitled";

    public function describe(): string
    {
        return "Book: " . $this->title;
    }
}

$book = new Book();

echo $book->describe();
Output
OUTPUT
Book: Untitled

The parts

Text
PLAIN
class ClassName
{
    // properties
    // methods
}
  • class is the keyword.
  • Book is the name. Use PascalCase: each word starts with a capital, no underscores (ShoppingCart, UserProfile).
  • The braces hold the members of the class.

Class vs object

ClassObject
What is itThe blueprintOne thing made from the blueprint
How manyOneAs many as you like
Created withclass Book { }new Book()

Think of a cookie cutter (class) and cookies (objects).

Naming rules

  • Class names are not case-sensitive in PHP, but write them exactly: Book, not book.
  • They cannot be PHP keywords (class, new, array).
  • Use a clear noun: Invoice, Customer, EmailSender.

One class per file

By convention, each class lives in its own file with the same name.

Text
PLAIN
src/
├── Book.php        <- class Book
├── Author.php      <- class Author
└── Library.php     <- class Library

This is what makes autoloading possible. PHP finds Book.php for you when the class is first used. See Autoloading.

Book.php
PHP
<?php
declare(strict_types=1);

class Book
{
    public function __construct(public string $title) {}
}
index.php
PHP
<?php
require_once __DIR__ . "/Book.php";

$book = new Book("PHP Basics");

echo $book->title;
Output
OUTPUT
PHP Basics

Class names and strings

Book::class gives the class name as a string. It is better than typing "Book", because a rename in your editor updates it.

index.php
PHP
<?php
class Book {}

echo Book::class;
Output
OUTPUT
Book

Anonymous classes

For a one-time object you can write a class without a name.

index.php
PHP
<?php
$logger = new class {
    public function log(string $message): void
    {
        echo "[log] $message";
    }
};

$logger->log("Started");
Output
OUTPUT
[log] Started
lightbulb
Start small
A class with two properties and one method is a good first class. Add more only when the code needs it.