PHP class Keyword
last modified November 25, 2026
The PHP class keyword declares a named type with properties and methods. A class is the blueprint; an object is one instance of it, created with new, and each object keeps its own property values while sharing the methods.
This article shows the declaration itself: properties, methods, constructors, visibility, the ::class name, and the errors that appear when a class is used incorrectly. Inheritance and the other class modifiers have their own articles, linked at the end.
Basic definitions
A class declaration starts with the keyword, then a name, then a body in braces. The body holds properties, which are variables belonging to the object, and methods, which are functions with access to those properties through $this.
Properties and methods can carry a visibility modifier. public members are reachable from anywhere, protected members from the class and its subclasses, and private members only from the declaring class. A property can also declare a type, and a typed property starts uninitialized until a value is assigned.
The class name is not a variable, so it has no $ prefix. By convention class names use PascalCase, one class occupies one file, and the file is named after the class. The PHP OOP tutorial covers the wider object model, while this page concentrates on the declaration syntax.
A minimal class
The first example declares a rectangle with two properties and one method that uses them.
<?php
declare(strict_types=1);
class Rectangle
{
public float $width;
public float $height;
public function area(): float
{
return $this->width * $this->height;
}
}
$rect = new Rectangle();
$rect->width = 3.0;
$rect->height = 4.5;
echo "Area: ", $rect->area(), "\n";
new Rectangle() creates an object and returns it. The properties are assigned from outside, then area() multiplies them through $this, which always points at the object the method was called on. Because the properties are typed as float, assigning a string raises a TypeError under strict_types.
$ php class_basic.php Area: 13.5
Constructors and typed properties
A constructor is the method PHP calls automatically after new creates the object. It is the right place to receive the values the object needs and to reject an invalid state early.
<?php
declare(strict_types=1);
class Rectangle
{
public function __construct(
public float $width,
public float $height,
) {
}
public function area(): float
{
return $this->width * $this->height;
}
}
$rect = new Rectangle(3.0, 4.5);
$square = new Rectangle(2.0, 2.0);
echo "Rectangle: ", $rect->area(), "\n";
echo "Square: ", $square->area(), "\n";
The constructor parameters are declared with a visibility modifier, which promotes them to properties in one step. Rectangle(3.0, 4.5) and Rectangle(2.0, 2.0) produce two independent objects: changing one would not touch the other. Constructor property promotion is explained in constructor property promotions, and a constructor with many optional values usually reads better with named arguments.
$ php class_constructor.php Rectangle: 13.5 Square: 4
Encapsulation with visibility
A class should expose the operations that are safe and hide the data that must stay consistent. Visibility is what enforces that boundary.
<?php
declare(strict_types=1);
class Account
{
private float $balance = 0.0;
public function __construct(public string $owner)
{
}
public function deposit(float $amount): void
{
$this->balance += $amount;
}
public function withdraw(float $amount): bool
{
if ($amount > $this->balance) {
return false;
}
$this->balance -= $amount;
return true;
}
public function balance(): float
{
return $this->balance;
}
}
$account = new Account("Alice");
$account->deposit(100.0);
echo $account->owner, " has ", $account->balance(), "\n";
echo $account->withdraw(150.0) ? "paid\n" : "declined\n";
echo $account->withdraw(40.0) ? "paid\n" : "declined\n";
echo "Left: ", $account->balance(), "\n";
$balance is private, so the only way to change it is through deposit() and withdraw(). The withdrawal method checks the funds first and returns false instead of allowing a negative balance, while balance() provides read access. The owner property is public because it is descriptive data that cannot break an invariant. The private and public keyword pages cover each modifier, and protected covers the third.
$ php class_visibility.php Alice has 100 declined paid Left: 60
Class names and ::class
Class names are case-insensitive, although the declared spelling should be used everywhere. The ::class constant returns the fully qualified name as a string, which is useful for logging and for APIs that take a class name.
<?php
declare(strict_types=1);
class Newsletter
{
public function name(): string
{
return self::class;
}
}
$newsletter = new newsletter();
echo $newsletter->name(), "\n";
echo Newsletter::class, "\n";
new newsletter() works because PHP matches the name without regard to case, but the output still shows the declared Newsletter. Inside the class, self::class refers to the current class, and the same constant can be written from outside as Newsletter::class. In a namespaced file the constant includes the namespace, which saves building the string by hand. The PHP namespaces article explains that resolution.
$ php class_name.php Newsletter Newsletter
Reading an undefined property
PHP allows a property to be read even when it was never declared or assigned, but the read is not silent. It produces a warning and evaluates to null.
<?php
declare(strict_types=1);
class Rectangle
{
public float $width;
public float $height;
public function area(): float
{
return $this->width * $this->height;
}
}
$rect = new Rectangle();
$rect->width = 3.0;
$rect->height = 4.5;
echo $rect->area(), "\n";
echo $rect->depth, "\n";
$depth does not exist on Rectangle, so the last line reports Undefined property: Rectangle::$depth and prints nothing for the value. The warning names the class and the property, which is usually enough to spot a typo or a missing assignment. Creating properties on the fly is deprecated since PHP 8.2, so a class should declare every property it uses.
$ php class_property.php 13.5 Warning: Undefined property: Rectangle::$depth in /app/class_property.php on line 21
Declaring the same class twice
A class name may exist only once in a request. Declaring it again is a fatal error, and the message points at both declarations.
<?php
declare(strict_types=1);
class Report
{
public int $rows = 0;
}
class Report
{
public int $pages = 0;
}
PHP refuses to compile the file, so nothing in it runs. The usual causes are two copies of a file included without require_once, or a class imported under the wrong name. The (previously declared in ...) part of the message identifies the first file, and the line after it identifies the second. The require_once article explains the inclusion rule that prevents this.
$ php class_duplicate.php
Fatal error: Cannot redeclare class Report (previously declared in /app/class_duplicate.php:5) in /app/class_duplicate.php on line 10
Stack trace:
#0 {main}
$this outside an object
$this exists only inside an instance method. Using it in a plain function is a runtime error, because there is no object to point at.
<?php
declare(strict_types=1);
function total(): float
{
return $this->amount;
}
echo total(), "\n";
The call reaches total(), which then fails with Using $this when not in object context. A static method has the same restriction: it belongs to the class rather than an instance, so it cannot use $this and must work with static properties or parameters instead. The static keyword article covers that case.
$ php class_this.php
Fatal error: Uncaught Error: Using $this when not in object context in /app/class_this.php:7
Stack trace:
#0 /app/class_this.php(10): total()
#1 {main}
thrown in /app/class_this.php on line 7
Best practices
Keep a class focused on one responsibility, and let the declaration state as much as possible about valid objects.
- Declare every property, type it, and initialize it in the constructor; do not create properties at run time.
- Keep properties private or protected and expose methods that preserve the class invariants.
- Use constructor property promotion for simple value objects, and a normal constructor when validation needs a body.
- Use PascalCase for the class and the file name, and rely on
::classinstead of repeating the name as a string. - Leave inheritance, interfaces, and traits to the articles that own those keywords; a class that needs none of them is easier to test.
Continue with PHP extends keyword for inheritance, PHP interface keyword for contracts, and PHP new keyword for object creation.
Source
PHP manual: classes and objects
This article covered the PHP class keyword: the declaration, typed properties, methods, constructors, visibility, ::class, and the errors raised by undefined properties, duplicate declarations, and $this outside an object. Continue with PHP OOP for the full object model, or read PHP clone keyword to copy the objects you have created.
Author
List all PHP tutorials.