0
0
PHPprogramming~5 mins

Object instantiation with new in PHP

Choose your learning style9 modes available
Introduction

We use new to create a fresh object from a class. It helps us make many things that behave the same way but hold different data.

When you want to create a new user profile in a website.
When you need to make multiple cars with different colors and speeds in a game.
When you want to keep track of different books in a library system.
When you want to create a new bank account with its own balance and owner.
Syntax
PHP
$object = new ClassName();

The new keyword tells PHP to make a new object from the class.

The parentheses () can hold values if the class has a constructor that needs them.

Examples
This creates a new object called $car from the class Car.
PHP
$car = new Car();
This creates a new User object and sends 'Alice' to the constructor.
PHP
$user = new User('Alice');
This makes a new Book object with default settings.
PHP
$book = new Book();
Sample Program

This program creates two dogs with different names using new. Each dog can bark and say its name.

PHP
<?php
class Dog {
    public string $name;
    public function __construct(string $name) {
        $this->name = $name;
    }
    public function bark(): string {
        return "Woof! I am {$this->name}.";
    }
}

$dog1 = new Dog('Buddy');
$dog2 = new Dog('Max');

echo $dog1->bark() . "\n";
echo $dog2->bark() . "\n";
OutputSuccess
Important Notes

Every time you use new, PHP makes a separate object with its own data.

If the class has a constructor, you must pass the right values inside the parentheses.

Objects let you group data and actions together, making your code easier to manage.

Summary

Use new to create a new object from a class.

Each object can have its own data and behavior.

Constructors can accept values to set up the object when created.