Access properties without knowing name

Asked

Viewed 83 times

6

You can access all your settings inside the class (estates) without having their names?

For example, if I create an instance of a class $classe = new Classe(), and I’m defining things in her:

$classe->ComprarFile = true;
$classe->comidaDoCachorro = false;
$classe->valorDoDolar = '50 reais';

It would be possible to access these properties in the class without knowing their name?

1 answer

6


Has. There are basically two options. One is using get_object_vars():

var_dump(get_object_vars($classe));

And the other is iterate over the object:

foreach ($classe as $key => $value) print "$key => $value\n";

There you can use creativity to access in different ways using these techniques. The important thing is that in the background the classes are arrays membership. So you have easy the names and values of all members.

  • can do this within the class itself?

  • 1

    Yes, you can. The example I used was taken from the documentation page that does just that. He uses the $this. Just be careful not to use an unnecessary and conceptually wrong resource.

Browser other questions tagged

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