function to convert object into array does not loop into foreach

Asked

Viewed 147 times

-2

I made the function down to pass by one Object of PHP class for a array, also PHP.

 /* Converte um objeto em array() */
  public function ObjToArray ($_obj) {

    $array = null;

    print_r( $_obj ); //funciona normalmente, imprime o objeto

    foreach ($_obj as $key => $value) :

       print "Key: " . $key . " VALUE: " .$value."<br>"; //não imprime, não entra aqui.
       $array [$key] = $value;

    endforeach;

    return $array;

  } 

The print_r( $_obj ) works normally.

But it doesn’t enter the foreach.

Where will be the mistake?

  • It would not be simpler to convert the object using a Typecast?

  • give an example of Typecast? Making the conversion in the class itself?

  • It would be something like that $meuArray = (array) $meuObjeto;.

1 answer

0

There is no logic error in your function, but if you say you are not entering foreach, the most likely reason is that the properties of your object are private.

A foreach loop only accesses public properties of an object, unless of course this loop is executed within a method of its object, as an object can access its own private properties.

So I believe your options are these

-Declare the Objtoarray function as a method in your target class.

Or

-Declare the properties you want to be passed to an array as public.

  • exact. had already done so, I was just wondering if there was a native function that did this when attributes are private

Browser other questions tagged

You are not signed in. Login or sign up in order to post.