How to Initialize an Object in PHP


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

Initializing an object means that we give an object that has been created from a class a value or values.

For example, say we create an object named car from the vehicles class. The vehicles class represents a range of vehicles and the car is just a particular object or instance of this vehicles class. We can then assign values to the car such as the car's color, the car's cost, the car's engine, etc. If we set the car's color to red, we have initialized the object with this color property.

So initialized an object is just giving values to the object, that represent's the object's properties.

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 below in the PHP code is the general standalone to initialize properties of an object.

So in the above code, we have initialized the color, type, and doors properties of the $car object.

All you need to do to initialize an object in PHP is to take the object name and use "->" followed by the property name. You then set this equal to the property value either through single quotes, double quotes, or nothing (if the value is a number, you have this option).

And that is all you need to do to initialize object properties in PHP.

Below we show the full PHP code of how to initialize an object and how to echo out the values of the object that we've initialized.

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.

Inside of the class we put a public variable $enginetype and set it equal to "automatic". You'll see now that every object we create will have an engine type of automatic. Because every object inherits the engine type being equal to automatic.

When we create the object o the class below named $car, it inherits this enginetype as being automatic.

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've initalized a few values, the type, color, and doors properties.

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 a basic example of how to initialize and output the initialized values of an object in PHP.

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 number of doors: 4
Car engine type: automatic

HTML Comment Box is loading comments...