9

I'm trying to write a function that formats every (string) member/variable in an object, for example with a callback function. The variable names are unknown to me, so it must work with objects of all classes.

How can I achieve something similar to array_map or array_walk with objects?

3 Answers 3

13

use get_object_vars() to get an associative array of the members, and use the functions you mentioned.

btw, you can also do a foreach on an object like you would on an array, which is sometimes useful as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that in the rare case when you're using an ArrayObject, you can do something like $obj->exchangeArray(array_map('func', $obj->getArrayCopy()));
1

You can use get_object_vars(), but if you need more control, try using reflection. It's slower than get_object_vars() (or get_class_methods() for that matter), but it's much more powerful.

1 Comment

that's a really cool functionality of php i didn't know about! I'm not exactly sure how I'd actually use it, but that's still cool!
0

You are looking for get_object_vars / get_class_methods (the first gets the variables, the second the method names).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.