0

Maybe someone can help explain the strange behaviour with this anon object:

$equipTest = (object) [
  $leakageLimit = "",
  $description = "",
  $location = "",
  $text = "",
 ];
$description = "";

In the following loop, I can assign values to $leakageLimit with no issues.

$equipTest->leakageLimit = $temp; 

But $location will not let me concatenate to it with out an error/notice:

$equipTest->location .= $temp; 

Results in:

Notice (8): Undefined property: stdClass::$location

As it did for $equipTest->description until I declared a temp var outside the loop. I assigned values to the temp description in the loop with:

$description .= $temp; 

And then assigned it to the object at the end of the loop with:

$equipTest->$description = $description;

Why can't I concatenate to this anonymous object? It was OK before when I had it as part of a fully declared class.

Cache Staheli
  • 3,510
  • 7
  • 32
  • 51
Byte Insight
  • 745
  • 1
  • 6
  • 17
  • 1
    Start with `print_r($equipTest)` I bet you'll be suprised – u_mulder Feb 03 '17 at 17:28
  • How to create anonymous object with php7. Checkout these links: https://wiki.php.net/rfc/anonymous_classes http://stackoverflow.com/questions/6384431/creating-anonymous-objects-in-php – Nitin Feb 03 '17 at 17:32

2 Answers2

2

This code

[
  $leakageLimit = "",
  $description = "",
  $location = "",
  $text = "",
]

does not mean

create array with four named elements and init each of them with empty string.

It means

create array of four numeric-indexed elements and set value of every element as a result of assigning an empty string to a variable.

And result of assigning is a value being assigned, i.e. - empty string.

So, if you

print_r([
  $leakageLimit = "",
  $description = "",
  $location = "",
  $text = "",
]);

you will see array with 4 empty values. And also your variables $leakageLimit, $description, $location, $text will be set to empty string.

So, if you want to create object with four named properties, your code is:

$equipTest = (object) [
  'leakageLimit' => "",
  'description' => "",
  'location' => "",
  'text' => "",
];
u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

Part of your problem is you're casting an array to an object. That produces unpredictable things sometimes, and it has here. If you var_dump($equipTest) what you'll get back is

object(stdClass)#1 (4) {
  [0]=>
  string(0) ""
  [1]=>
  string(0) ""
  [2]=>
  string(0) ""
  [3]=>
  string(0) ""
}

You'll note that it didn't keep the keys like you were expecting. When you do

$equipTest->leakageLimit = 'someval';

It actually creates the variable.

object(stdClass)#1 (5) {
  [0]=>
  string(0) ""
  [1]=>
  string(0) ""
  [2]=>
  string(0) ""
  [3]=>
  string(0) ""
  ["leakageLimit"]=>
  string(7) "someval"
}

If I were you, I'd make a class that defines these values first, then you can concatenate them. It avoids the nasty side effects of casting

Community
  • 1
  • 1
Machavity
  • 30,841
  • 27
  • 92
  • 100