How to Create an Object in PHP with new
A class describes a kind of object; new makes one. You give the class's constructor the values it needs, and get back an object whose methods you call with ->.
Syntax
$<object> = new <ClassName>(<arguments>);
$<object>-><method>(<arguments>);
| Part | What it does |
|---|---|
new <ClassName>(...) | Creates an object and runs the class's constructor with the arguments. |
$<object> | A variable holding the new object. |
-><method>(...) | Calls one of the object's methods. |
The PHP manual on classes and objects: "To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an Exception on error."
The Example
The example creates a DateTimeImmutable, PHP's built-in date and time class, for 26 November 2026 at 09:30, then prints the day of the week and the date.
Prerequisites
- PHP for the command line. This guide uses PHP 8.6.0.
Step 1: Write the Code
Create a file named main.php:

<?php
$date = new DateTimeImmutable('2026-11-26 09:30:00');
echo $date->format('l'), "\n";
echo $date->format('Y-m-d H:i'), "\n";
format('l') gives the full day name, and 'Y-m-d H:i' the date and time.
Step 2: Run It
php main.php
Thursday
2026-11-26 09:30

The constructor read the text and built a date object; its methods then formatted it. The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Passing a value the constructor can't use, as in new DateTimeImmutable('not a date') | Fatal error: Uncaught DateMalformedStringException: Failed to parse time string (not a date) at position 0 (n): The timezone could not be found in the database | Pass a valid value, or catch the exception |
Leaving out new, as in DateTimeImmutable('2026-11-26') | PHP looks for a function with that name and stops with Call to undefined function | Write new DateTimeImmutable(...) |
Using . instead of -> to call a method | . joins strings in PHP | Use -> |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Class "…" not found | The class name is wrong, or its file isn't loaded | Check the name and its namespace |
| An exception from the constructor | The arguments are invalid | Read the message and fix the value |
FAQ
What's the difference between DateTime and DateTimeImmutable?
Methods of DateTimeImmutable, such as modify, return a new object and leave the original unchanged; DateTime changes itself.
Can I create my own classes?
Yes, with class Name { ... }, and new Name() creates objects from them the same way.
Conclusion
new ClassName(arguments) creates an object and runs its constructor; $object->method() uses it. A constructor that can't use its arguments throws an exception.
Additional Resources
- The basics of classes and objects, in the PHP manual.
- DateTimeImmutable, in the PHP manual.
