Beamtic's logo
  1. Create user
Home

Share via:

PHP: Arrays vs Objects

Learn about the difference between arrays and objects, and why objects are more powerful than arrays.

237 views

Edited: 2020-06-21 13:24

Objects vs arrays, PHP

For data storage in PHP, objects are more powerful than arrays, since they also make it possible to add and use methods and change certain default behaviors of the object via magic methods.

You can use an object to store key and value pairs in a similar way to how you would in arrays. When a pair is added to the object, it will can be stored in properties (variables) of the object. Once an object is instantiated, you will be able to add new properties from outside like this:

$myObject->newProperty = 'Hallo World';
echo $myObject->newProperty;

As with arrays, we may even use the foreach loop to iterate over the the properties in our object:

$containerObject = new stdClass();
$containerObject->one = 1;
$containerObject->two = 2;

foreach ($containerObject as $property_name => $value) {
  echo $property_name .' '. $value . PHP_EOL;
}

Anonymous classes in PHP 7

PHP 7 improved OOP even further by adding support for on-the-fly anonymous classes, avoiding the use of the generic, and clumsy, stdClass when spewing out object "data containers".

For example, the below example is created on-the-fly within an existing class:

// Anonymous class
$containerObject = new class() {
  public $one;
  public $two;
};

$containerObject->one = 1;
$containerObject->two = 2;
$containerObject->three = 3;

foreach ($containerObject as $property_name => $value) {
  echo $property_name .' '. $value . PHP_EOL;
}

For all intends and purposes, this is the equivalent of creating a traditional class. We can even add magic methods to the class. For example, using __set() we may prevent adding properties from the outside:

public function __set($name, $value) {
  throw new \Exception("Adding new properties is not allowed on this object");
}

Allowed characters in variables

As you may know, with arrays, we can use any string as a key name, but when using object properties we will normally be limited to using underscores, letters and numbers.

There is at least couple of ways around this problem:

  1. We can use variable variables to allow special characters in the variable name.
  2. We can use an array inside the object.

A dynamically named variable can be assigned like this:

$a = '##'; // Name of the variable

$$a = 'Hallo World'; // Data in the variable

echo ${'##'}; // Output the variable

Or, even easier:

${'%&¤'} = 'Hallo World';
echo ${'%&¤'};

To declare a property with special characters in an OO context, we may do like:

$myObject->${'##'} = 'Hallo World'; // Assign value
echo $myObject->${'##'}; // Output data

Comments