Is there any advantage to conditionally defining functions in PHP? For example, if I have a script similar to this
function abc() {
...
}
function xyz() {
...
}
if (user_is_logged_in()) {
...
abc();
...
xyz();
}
else echo 'Not logged in.';
Would there be any advantage, and would it be legal, to move those function definitions inside the if statement? I don’t know much about the back end of PHP, but it seems like the server could potentially have to do a lot of work defining the functions, and then have them never be used.
I wouldn’t worry about “the server having a lot of work to do” with defining a lot of functions. In all likelihood, this is not going to be a bottleneck in your application.
I would advise against the design of conditional function definition, in PHP or any language. Rather, you can define the logic within the function. For example, within the abc() function, you can provide if/else logic that checks to see if the user is logged in.
Alternatively, you can use class methods and objects to make your code cleaner and easier to understand. If you understand OO, that would be the way to go.