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.
<?php
class Book
{
public string $title = "Untitled";
public function describe(): string
{
return "Book: " . $this->title;
}
}
$book = new Book();
echo $book->describe();
Book: Untitled
The parts
class ClassName
{
// properties
// methods
}
classis the keyword.Bookis 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
| Class | Object | |
|---|---|---|
| What is it | The blueprint | One thing made from the blueprint |
| How many | One | As many as you like |
| Created with | class 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, notbook. - 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.
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.
<?php
declare(strict_types=1);
class Book
{
public function __construct(public string $title) {}
}
<?php
require_once __DIR__ . "/Book.php";
$book = new Book("PHP Basics");
echo $book->title;
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.
<?php
class Book {}
echo Book::class;
Book
Anonymous classes
For a one-time object you can write a class without a name.
<?php
$logger = new class {
public function log(string $message): void
{
echo "[log] $message";
}
};
$logger->log("Started");
[log] Started