0

I'm trying to create new object from an array of values. I don't know to create new object. So I added following lines.

$object = (object) '';
$object->vehicleId = $vehicleId;

But it automatically adds a new property scalar in the object. How to remove it?

Dharman
  • 30,962
  • 25
  • 85
  • 135
eduard
  • 67
  • 1
  • 9

3 Answers3

1

As per the PHP Manual:

If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. An array converts to an object with properties named by keys and corresponding values. Note that in this case before PHP 7.2.0 numeric keys have been inaccessible unless iterated.

When you cast a string to an object the value of that string will be saved as an attribute. The default name is given which is scalar. Even an empty string is still considered to hold a value.

In PHP you have multiple ways of creating an empty object.

An example taken from https://www.php.net/manual/en/language.types.object.php#118679

<?php
$obj1 = new \stdClass; // Instantiate stdClass object
$obj2 = new class{}; // Instantiate anonymous class
$obj3 = (object)[]; // Cast empty array to object

var_dump($obj1); // object(stdClass)#1 (0) {}
var_dump($obj2); // object(class@anonymous)#2 (0) {}
var_dump($obj3); // object(stdClass)#3 (0) {}

Another way would be to cast a null value to an object as N69S shown:

$object = (object)null; // Same as (object)[]

And of course you can convert an associative array to an object:

$object = (object)['a' => 123];

// object(stdClass)#1 (1) {
//   ["a"]=>
//  int(123)
// }
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

You can instantiate an object stdClass with new:

$object = new stdClass();
$object->vehicleId = $vehicleId;
Dharman
  • 30,962
  • 25
  • 85
  • 135
Jean Marcos
  • 1,167
  • 1
  • 12
  • 17
0

you can just do it the conventional way

$object = new \stdClass();

or with null conversion

$object = (object)null;

and if you already have an array, you can convert it to object

$object = (object)$array;
N69S
  • 16,110
  • 3
  • 22
  • 36