Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling reset with object?

Tags:

php

I was surprised to see the reset function work on objects.

<?php

class C {
  private $a = 'a';
  protected $b = 'b';
  public $c = 'c';
}

$c = new C;
echo reset($c); // a

It looks like if reset receives an object it first casts it to an array? This is not mentioned anywhere in the documentation. Is this an implementation detail?

like image 658
csirmazbendeguz Avatar asked Feb 23 '19 21:02

csirmazbendeguz


1 Answers

The object is not cast into an array. It is native feature of the reset() function to accept an object and use it's property table (although this functionality is not really documented anywhere)

But if you check out the implementation of reset() in the PHP interpreter you see it defines the function parameter as a Z_PARAM_ARRAY_OR_OBJECT_HT_EX which according to the internal docs means (emphasis mine):

Z_PARAM_ARRAY_OR_OBJECT_HT

Specify a parameter that should parsed as either an array or an object into a HashTable. If the argument is an object, then the object's property table will be used.....

— phpinternals

Other functions that uses this type of parameter include current() and next() which may also accept an object as input.

like image 186
Daniel Avatar answered Nov 05 '22 23:11

Daniel