views:

61

answers:

4

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.

+2  A: 

It is definitely legal, but I would recommend against it, because it will decrease the readability/maintainability of course code considerably.

Use a op code cache (like APC) instead, this will reduce the load on the server.

Drupal devs did a benchmark for different op code caches, and also compared PHP without op code cache, You can see the results at http://2bits.com/articles/benchmarking-drupal-with-php-op-code-caches-apc-eaccelerator-and-xcache-compared.html

Anti Veeranna
I don't own the server.
Shadow
+3  A: 

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.

jonstjohn
Using OO for big stuff, but for certain components of this project, it just slows me down, as the code isn't re-used anywhere else. Thanks for the answer, though.
Shadow
A: 

I think, but might be wrong, that you would need to adjust the syntax to create anonymous functions, e.g.:

<?php
if(a) {
abc = function {
function stuff
}
} else if (b) {
xyz = function {
function stuff
}
}
?>
Note for future readers: This is PHP 5.3+ only.
Shadow
A: 

I learned very quickly not to optimize PHP before parsing like I would optimize C before letting gcc dig into it.

Don't worry about functions defined in PHP that are never used. Rather, put your effort into optimizing the functions that are actually reached. Of course, avoid duplicating code in 20 functions that do almost the same thing ... but that's a given in any language.

Tim Post