How to Instantiate an Object in PHP


In this article, we go over how to instantiate an object in PHP.

Instantiating an object means that we create a new object of a class in PHP.

Before you can create an object, you must create a class. The class is the overall blueprint or template of the object. So you must first have a class. Then once you have a class, you can create an object of a class.

So let's say we create a class named vehicles. Vehicles is the overall blueprint or template.

Inside of this vehicles class, we can create an object or several objects.

One object, for instance, can be a car. Another one can be a truck. Another object can be a boat. Another vehicle can be a van.

So from this class, which represents a sort of template, we can create objects of this class.

So below in the PHP code is the general standalone to create an object named car from the vehicles class.

So in the above code, we have created an object named $car from the vehicles class.

We show the full PHP code of how to instantiate an object below.

So in the above code, we've created a class named vehicles. To create a class in PHP, all you have to do is use the keyword class followed by the name of the class.

We then create an object of the class vehicles and name it $car. This is a new car object we've created.

After we've created this instance of a class, we can now do things with the object such as assign it properties. A car has a type, for example, being a toyota camry. A car has a color, for example, green. A car has a cost. In our example, the car costs $20,000.

I echoed out the object properties just to show you how it would work to create an object, give it properties, and then output those properties.

So this is the most basic example of create an instance of a class. It can get more advanced than this. If the object takes values as parameters, then you would need to create a constructor method that is able to initialize the values to the object. But just to make this tutorial simple, I've just shown how to make the most basic type of object of a class that can be done with PHP.

In further tutorials, I'll show more.

Going back to the PHP code above, if it's run, this gives the following output shown below.

Actual PHP Output

Car type: Toyota Camry
Car color: Green
Car cost: $20,000

HTML Comment Box is loading comments...