Instantiating with new
Learn to create an instance from a class with the new operator.
Instantiating with new
To create an instance from a class you use the new operator. new Car() produces a new instance of the Car class and places it in memory.
The instance is usually assigned to a variable: $car = new Car();. Now $car is an instance of the Car class. The class definition is only a template; new turns that template into a running instance. You can create as many instances from the same class as you want.
Calling methods on an instance
After creating an instance, you can call methods and access properties with the -> operator. Example: $car->showBrand(); runs the showBrand method of the $car instance.
Accessing a property uses the same operator: $car->brand. With parentheses it is a method call, without it is a property access. The method reaches the instance data through $this and produces the output you want.
Exercise Call the Car class
Define a class named Car. Add the property public $brand = "Unknown";. Write a method showBrand; in the body write echo "Brand: " . $this->brand . "\n";. After the class, create an instance with $car = new Car(); and call the method with $car->showBrand();.
Show example solution
Define the class, then write $car = new Car(); and $car->showBrand();.
Example solution:
<?php
// Write the Car class and create an instance
class Car {
public $brand = "Unknown";
function showBrand() {
echo "Brand: " . $this->brand . "\n";
}
}
$car = new Car();
$car->showBrand();
Test yourself
-
Complete the instantiation
$car = ____ Car(); $car->showBrand();Show answer
$car = new Car(); $car->showBrand(); -
Which is the correct way to create an instance of the Car class?
- $car = Car();
- $car = new Car();
- $car = create Car();
- $car = class Car();
Show answer
$car = new Car(); — Correct. The new operator, the class name and parentheses create a new instance.
-
Match the instantiation parts
- new
- Operator
- Car
- Class name
- ()
- Parentheses
- $car
- Instance variable