Page 4 of 4
Of course if you dont' spot this then all sorts of things go wrong and many programmers conclude that they can't define functions within such include files. A fact that you can confirm if you scan though comments included in some Joomla modules which say something like "I have to repeat this code because I can't define a function".
Well you can define a function to avoid repeating code as long as you follow some simple rules. The rules are:
- define the function conditionally as shown above
- define any functions that you want to use at the start of the file
- you can't use $this but you can define a $that variable and pass it to your function
- you still can't access protected or private members using $that
In some cases the restriction to only using public members is a problem but usually it isn't. Equally if you also know that the method will only ever be executed once then you can also drop the conditional declaration and simply define the function in the usual way. Also if you do this then the functions will be defined as the include file is read in and you can define them anywhere - i.e. they don't have to be at the start of the file.
In short - you can use inner functions to divide up a method that you are writing as part of an include file.
Anonymous functions can be local
The reason that functions are global is simply that their name is defined at a global level. In PHP 5.30 and later there is another way to define a function however and in this case its "name" can be global or local.
An anonymous function is simply a function that you assign to a standard variable. The function's lifespan is determined by the variable. When the variable is destroyed so is the function. What this means is that now inner functions, stored in a local variable is indeed local.
This defines an inner annoymous function and you can call the function usng the variable as:
The good news is that not only is the anonymous function local to the containing function it is also subject to closure in that it can access the containing functions variables even if the containing function no longer exists.
There are two points to consider here. The first is that closures aren't as useful in a server side language as they are in a client side language. The reason is simply that closures are useful in callbacks and event handling and server side PHP uses far fewer of both. The second problem is that $this still isn't treated properly by the inner function. That is you still have to use the $that trick and you still can't access private and protected members.
There are a few other problems, you can copy function references and so on, and so in the main anonymous functions aren't as yet a great advance over the standard PHP function.