Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Keyword new

Allocate an instance and call its constructor with the supplied arguments.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

new Ticket(4)

Allocate an instance and call its constructor with the supplied arguments. A class name held in a string can select the class dynamically. Each new expression creates a separate instance. PHP 8.4 permits immediate member access without wrapping a parenthesized constructor call in another pair of parentheses.

class Ticket {public function __construct(public int $n) {}}
$type=Ticket::class; $a=new $type(3); $b=new Ticket(3); echo json_encode([$a===$b,new Ticket(4)->n]);
[false,4]

Examples

<?php
class Ticket {public function __construct(public int $n) {}}
$type=Ticket::class; $a=new $type(3); $b=new Ticket(3); echo json_encode([$a===$b,new Ticket(4)->n]);

Result

[false,4]

Sources