Skip to content

3 ways create PHP objects

Last updated on December 17, 2023

In PHP, sometime we need to create PHP objects to do some logical handlers. The definition of object in PHP is not distinguished clearly like JavaScript. We usually use object to create an instance of class.

Quick view

Overview

In PHP, sometime we need to create PHP objects to do some logical handlers. The definition of object in PHP is not distinguished clearly like JavaScript. We usually use object to create an instance of class.

class Foo()
{
    // Some methods and attributes
}

// Create object 1 for Foo class
$bar1 = new Foo;

// Create object 2 for Foo class
$bar2 = new Foo;

Create PHP objects by custom class

This method is very common, we can see a lot of practice for this. It is simply create a class and we call the class as object.

class Vehicles
{
    public function park()
    {
        echo "Safe parked";
    }
}

// Call Vehicles class
$Vehicles = new Vehicles;
$Vehicles->park();

// Check $Vehicles variable
echo gettype($Vehicles); // Output: object

Use stdClass() to create PHP objects

As usual usage, we always define an Array to create a block of information like this:

$vehicle = [
  'id'    => '1234',
  'year'  => '2022',
  'make'  => 'Subaru',
  'model' => 'Crosstrek'
]

We could create an object to do this instead:

$vehicle = new stdClass();
$vehicle->id    = '1234';
$vehicle->year  = '2022';
$vehicle->make  = 'Subaru';
$vehicle->model = 'Crosstrek;

// and call a item
echo $vehicle->make; // Output: Subaru

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified. But, if object type is converted/type-casted an instance of stdClass is created, if it is not NULL. If it is NULL, the new instance will be empty.

Uses:

  • The stdClass directly access the members by calling them.
  • It is useful in dynamic object.
  • It is used to set dynamic properties etc.

However, I do not recommend this way to transfer data. This is because stdClass() is a class. A class’s performance is slower than an Array. So that’s why we barely see people use stdClass() in their source code. Read more at: What is better stdClass or (object) array to store related data?

Converting to object and array or any variable

A better way and new to me that we can convert an array to object. For instance:

$vehicle = [
  'id'    => '1234',
  'year'  => '2022',
  'make'  => 'Subaru',
  'model' => 'Crosstrek'
]
$objVehicle = (object) $vehicles;

echo $objVehicle->make; // Output: Subaru

echo gettype($vehicle); // array

echo gettype($objVehicle); // object

Published in⌨️ Programming TipsBlogs

Comments are closed.