Conditionally defining functions

Is there any advantage to conditionally defining functions in PHP? For example, if I have a script like this

function abc() {
    ...
    }

function xyz() {
    ...
    }

if (user_is_logged_in()) {
    ...
    abc();
    ...
    xyz();
    }
else echo 'Not logged in.';

      

Was there any advantage, and would it be legal, to move these function definitions inside a statement if

? I don't know much about the end of PHP, but it looks like the server might have to work a lot to define the functions and then never use them.

+2


source to share


5 answers


I wouldn't worry about the "server has to work a lot" with a lot of functions defined. In all likelihood, this will not be a bottleneck in your application.

I would suggest developing a definition of conditional functions, in PHP or any language. Rather, you can define logic inside a function. For example, in the abc () function, you can specify if / else logic that checks if the user is logged in.



Alternatively, you can use methods and class objects to make your code more readable and understandable. If you understand OO, this is the way to go.

+4


source


This is definitely legal, but I would recommend against it because it will significantly reduce the readability / maintainability of the course code.

Use opcode cache instead (like APC), it will reduce server load.



Drupal devs did a test for various 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

+2


source


I very quickly learned not to optimize PHP before parsing, as if I were optimizing C before letting gcc dig into it.

Don't worry about PHP-defined functions that are never used. Rather, do your best to optimize the features actually achieved. Of course, avoid duplicating code in 20 functions that do almost the same thing ... but that's data in any language.

+2


source


I think, but it might not be right, that you will need to customize the syntax for creating anonymous functions, for example:

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

      

+1


source


The conditional definition should not be used as an optimization, but can be used in conjunction with function_exists

to provide alternative implementations or to be dropped if an extension is not available. Wordpress does the former with many features (like wp_hash_password

) to allow plugins to replace them.

0


source







All Articles