The New Operator

The new operator creates a new object of the specified class. In doing so, the class constructor is called if it is defined. The operator returns the created object, which can be assigned to a variable.

Syntax

php$object = new ClassName([arguments]);

Example

Let's create a simple class and its instance:

php<?php
  class User {
    public $name;
    
    public function __construct($name) {
      $this->name = $name;
    }
  }
  
  $user = new User('John');
  echo $user->name;
?>

Code execution result:

php'John'

Example

Creating an object without a constructor:

php<?php
  class Product {
    public $price = 100;
  }
  
  $product = new Product();
  echo $product->price;
?>

Code execution result:

php100

Example

Creating an anonymous class:

php<?php
  $obj = new class {
    public function sayHello() {
      echo 'Hello!';
    }
  };
  
  $obj->sayHello();
?>

Code execution result:

php'Hello!'

See Also

  • the class command,
    which declares a new class
  • the __construct method,
    which defines an object constructor