ZetCode

PHP new Keyword

last modified November 25, 2026

The PHP new keyword creates an object from a class. It calls the constructor, returns the instance as an expression, and is the starting point of almost every object-oriented program in PHP.

This article shows how new behaves with constructors, multiple instances, dynamic class names, anonymous classes, and the newer positions where the keyword is allowed.

Basic definitions

The new keyword creates an instance of a class. It allocates the object, runs its constructor, and produces the object as the value of an expression. The class must be known at run time: either it is declared earlier in the file, or an autoloader loads it when the name is used.

A variable does not contain the object itself; it holds an identifier that refers to it. Assigning one object variable to another copies that identifier, so both variables refer to the same instance. This is why changing a property through one variable is visible through the other, and why clone is needed for an independent copy.

The parentheses after the class name are optional when the constructor takes no arguments: new Car and new Car() are equivalent. When arguments are passed, they go inside the parentheses and are handed to the constructor.

Creating an object

The first example defines a class with two properties that have default values, then creates one object.

new_basic.php
<?php

declare(strict_types=1);

class Car
{
    public string $model = "unknown";
    public int $year = 2026;

    public function describe(): string
    {
        return "{$this->model} ({$this->year})";
    }
}

$car = new Car();
$car->model = "Toyota Corolla";

echo $car->describe(), "\n";
echo get_class($car), "\n";

The class declares no constructor, so new Car() uses the implicit one and the properties keep their defaults. The object is then modified through the -> operator. get_class confirms the class of the instance; on a modern codebase $car::class gives the same name without a function call.

$ php new_basic.php
Toyota Corolla (2026)
Car

Passing arguments to the constructor

A constructor receives the arguments written between the parentheses and normally stores them in properties.

new_constructor.php
<?php

declare(strict_types=1);

class Person
{
    public string $name;
    public int $age;

    public function __construct(string $name, int $age)
    {
        $this->name = $name;
        $this->age = $age;
    }

    public function introduce(): string
    {
        return "{$this->name}, {$this->age}";
    }
}

$person = new Person("Ada", 36);
echo $person->introduce(), "\n";

Both properties are declared first and assigned in __construct. The two arguments in new Person("Ada", 36) must match the parameter list, otherwise PHP raises ArgumentCountError or TypeError before the body runs. PHP also offers constructor property promotion, which declares and assigns the properties in the parameter list; it is described in PHP Constructor Property Promotions.

$ php new_constructor.php
Ada, 36

Separate instances and shared handles

Each new call creates a distinct object. Assignment, by contrast, only copies the handle to an existing object.

new_instances.php
<?php

declare(strict_types=1);

class Counter
{
    public int $value = 0;
}

$first = new Counter();
$second = new Counter();
$first->value = 5;

echo "first: {$first->value}, second: {$second->value}\n";

$third = $first;
$third->value = 9;

echo "first: {$first->value}, third: {$third->value}\n";
echo spl_object_id($first) === spl_object_id($third) ? "same object\n" : "different objects\n";

The first two objects are independent, so changing $first leaves $second at zero. The third variable is assigned from the first one, and both names now refer to the same instance: the update through $third is visible through $first, and spl_object_id returns the same number for both. To obtain an independent copy, use clone, which is explained in PHP clone keyword and is taught after this article.

$ php new_instances.php
first: 5, second: 0
first: 9, third: 9
same object

Class names from variables

The class does not have to be written literally after new. Any expression that evaluates to a class name can be used.

new_dynamic.php
<?php

declare(strict_types=1);

class Greeter
{
    public function greet(): string
    {
        return "Hello there";
    }
}

$class = Greeter::class;
$first = new $class();

$name = "Gre" . "eter";
$second = new $name();

$third = new ('Greeter')();

echo $first->greet(), "\n";
echo get_class($second), " and ", get_class($third), "\n";

Greeter::class produces the fully qualified name as a string, and new $class() instantiates it. A computed string works the same way, and an arbitrary expression must be wrapped in parentheses, as in new ('Greeter')(). Dynamic instantiation is common in factories and plugin systems; validate the name against a list of allowed classes before using it with untrusted input.

$ php new_dynamic.php
Hello there
Greeter and Greeter

Anonymous classes

new can also create a class that has no name. Constructor arguments go in parentheses between the keyword and the class body, as with a named class.

new_anonymous.php
<?php

declare(strict_types=1);

$logger = new class("app") {
    public function __construct(private string $channel)
    {
    }

    public function log(string $message): string
    {
        return "[{$this->channel}] " . $message;
    }
};

echo $logger->log("started"), "\n";
echo get_debug_type($logger), "\n";

The anonymous class takes the channel name in its constructor and uses it in log. get_debug_type reports class@anonymous, because the internal name contains the file and position and is not meant for display. Anonymous classes are useful for one-off implementations, especially in tests; the PHP Anonymous Classes tutorial covers them in detail.

$ php new_anonymous.php
[app] started
class@anonymous

new self inside a method

Inside a class, new self creates another instance of that same class. It is often used by methods that return a modified copy instead of changing the receiver.

new_self.php
<?php

declare(strict_types=1);

class Money
{
    public function __construct(public int $cents)
    {
    }

    public function withCents(int $cents): self
    {
        return new self($cents);
    }

    public function format(): string
    {
        return number_format($this->cents / 100, 2) . " EUR";
    }
}

$price = new Money(1250);
$discounted = $price->withCents(999);

echo $price->format(), "\n";
echo $discounted->format(), "\n";

withCents builds a new Money object and leaves the original untouched, so the two prices print different values. new self always refers to the class that contains the method. Late static binding, written new static and used when a subclass should produce an instance of itself, is covered in PHP static keyword.

$ php new_self.php
12.50 EUR
9.99 EUR

new in parameter defaults

Since PHP 8.1, new may appear in a parameter default value. The expression is evaluated when the function is called without that argument.

new_default.php
<?php

declare(strict_types=1);

class Logger
{
    public function __construct(private string $prefix = "[log]")
    {
    }

    public function write(string $message): string
    {
        return "{$this->prefix} {$message}";
    }
}

function run(Logger $logger = new Logger()): string
{
    return $logger->write("default logger");
}

echo run(), "\n";
echo run(new Logger("[test]")), "\n";

The first call omits the argument, so a fresh Logger with the default prefix is created. The second call passes its own instance. The same allowance applies to static variable initializers, global constants, and attribute arguments, but not to property defaults or class constants. Use it for small, stateless helper objects; a service that needs configuration is better injected explicitly.

$ php new_default.php
[log] default logger
[test] default logger

Best practices

Object creation is easy to scatter through a codebase; the guidelines below keep it in places that can be tested.

Source

PHP manual: classes and objects

PHP manual: constructors and destructors

PHP manual: anonymous classes

This article explained the PHP new keyword: object creation, constructor arguments, separate instances, dynamic class names, anonymous classes, new self, and new in parameter defaults. Continue with PHP class keyword for declaring classes, PHP clone keyword for copying objects, and PHP Constructor Property Promotions for shorter constructors.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all PHP tutorials.