Site icon Hip-Hop Website Design and Development

Adding to an array & passing it through do_action/apply_filters

For exercise I am working through a PHP class to add meta boxes I found on GitHub. I just copied the code and now I am playing around with it to understand it.

It works like this: The file containing the class is included on init. Inside that file, but outside the class, an empty array $meta_boxes is initialized.
After that, a custom action is executed, using apply_filters. My guess is apply_filters is used instead of do_action because the latter does not return anything – $meta_boxes = apply_filters( 'cmb_meta_boxes', $meta_boxes ).

Into that action, a function is hooked which adds to the existing array, which is returned at the end.

That function gets $meta_boxes passed as an argument.

TLDR;
An empty array is created, a function which adds to that array and returns it is fired. The function fires because it is hooked to a custom hook which is executed using apply_filters, because that way the function’s return value can be assigned to a variable.

To me, that seems really to be a really complicated task for a pretty simple thing. Is this ‘the WordPress way’ of doing things or can the same result achieved with less code?

Why does the function that is hooked into the custom filter/action needs the array as an argument. Isn’t it passed automatically to that function because it is added to the hook?

Maybe I haven’t yet fully understood the way variables are handled inside WordPress. If you think this is the case, any links to explanations would be also gladly accepted.