0

If we have a PHP array and want to cast it to an object, is it necessary to reassign the variable? and is there any performance benefits to this?

$key_value = ('key1'=>'value1' , 'key2'=>'value2');

$key_value = (object)$key_value; //We can reassign as an object

//Is there a way to, without reassigning, just cast the type of the already assigned variable?
//Is this advantageous in terms of performance?
(object)$key_value; //is this the correct syntax, considering it is even possible?

In most cases this is probably irrelevant, but it got me curious towards the theory behind it.

u_mulder
  • 54,101
  • 5
  • 48
  • 64
David Neto
  • 809
  • 1
  • 12
  • 20
  • So try this code and tell us. – u_mulder Jul 10 '18 at 11:59
  • @u_mulder thanks for your answer, I'm interested in the theory behind it as stated in the question. – David Neto Jul 10 '18 at 12:01
  • I think performance hits are negligible. Casting is on the order of CPU cycles, which take less than 1 nanosecond to do. If you set out nanoseconds to other "trivial" tasks like looking up a file, that is orders of magnitude smaller and you will probably not notice it ever: https://twitter.com/rzezeski/status/398306728263315456 – Loek Jul 10 '18 at 12:03
  • 2
    This is actually 2 questions - the first of which,*"If we have a PHP array and want to cast it to an object, is it necessary to reassign the variable?"* can be simply answered - nope. And the second, *"is there any performance benefits to this?"* is probably going to be answered with some kind of digital shrug - *meh* maybe? The difference will be minimal, possibly worse. – CD001 Jul 10 '18 at 12:04

1 Answers1

4

settype() is the only way to change the type of a variable in-place. Every other mechanism returns a new value instead.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358