简体   繁体   中英

Conditionally defining functions

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.

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

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.

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

<?php
if(a) {
abc = function {
function stuff
}
} else if (b) {
xyz = function {
function stuff
}
}
?>

Conditional definition shouldn't be used as an optimization, but can be used in combination with function_exists to provide alternate implementations or to create fall-backs in case an extension isn't available. Wordpress does the former with many functions (eg wp_hash_password ) to allow plug-ins to replace them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM