[wp-hackers] add_filter before or after function?

DD32 wordpress at dd32.id.au
Thu Aug 30 02:17:30 GMT 2007


On Thu, 30 Aug 2007 11:54:47 +1000, Jeremy Visser
<jeremy.visser at gmail.com> wrote:

> DD32 wrote:
>> add_filter('query_vars', 'test_queryvars' );
>> function test_queryvars( $qvars ){
>>     $qvars[] = 'artist_slug';
>>     $qvars[] = 'artist_page';
>>     return $qvars;
>> }
>
> I notice you add the add_filter() _before_ you declare the actual
> function. Others do that too, while other add the add_filter() (or
> add_action()) _after_ the function.
>
> Which is best?

I put it directly before the function so i know what the function is
hooked to, The only time i dont do that is if the hook is added within
another function.
But which one is better?
It all depends on your coding style i guess, I feel important things
should be at the start of the function(documentation/hooks/etc), Others
however, Seem to like writing the function, and then adding the hooks for
the function afterwards, Theres no "Best" way, both work, Just depends how
your mind thinks i guess.

> I tend to put it after the function because, well, if you put it before,
> aren't you referencing a non-existant function? What if add_filter() one
> day adds a check to see if the function_exists()? If you do add_filter()
> first, then won't it break?

Before PHP executes a document, it first parses the file, So it knows what
functions are declared within a PHP file, When you include a file, PHP
Parses the file, and then continues execution.
But add_filter only accepts a string of the function name anyway, So it
doesnt actually call the function until the apply_filters call is run.
Thats also why when you've got a fatal error in a PHP document PHP fails
as soon as the page with the error is loaded.

In certain other languages however, You cant do that, They parse the
document from top-down, executing commands as they go, if you reference a
function later in the file, it'll throw an error because the language
hasnt yet located that function.

PHP Spends quite a lot of time parsing the documents, Thats why programs
such as eAccellerator and the Zend applications are used, They cach the
parsed documents so they dont need to be read again, PHP simply loads the
pre-parsed documents from memory.



Bah! Sent this using the wrong email :), It'd be so nice if the list was  
to bounce messages.. But at the same time.. it'd generate too much  
traffic..


More information about the wp-hackers mailing list