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
$object = new ClassName([arguments]);
Example
Let's create a simple class and its instance:
<?php
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
$user = new User('John');
echo $user->name;
?>
Code execution result:
'John'
Example
Creating an object without a constructor:
<?php
class Product {
public $price = 100;
}
$product = new Product();
echo $product->price;
?>
Code execution result:
100
Example
Creating an anonymous class:
<?php
$obj = new class {
public function sayHello() {
echo 'Hello!';
}
};
$obj->sayHello();
?>
Code execution result:
'Hello!'
See Also
-
the
class
command,
which declares a new class -
the
__construct
method,
which defines an object constructor