PHP custom function scope / good practice
I have script which has the following structure:
<?php
if( a == b ){
function some_function_name(){
// do something here
}
if( c 开发者_Go百科== d ){
some_function_name();
}
}
?>
I get an error message saying that some_function_name(); does not exist.
What am I doing wrong and is this good practice?
I want to create a function, because I have a bunch of steps which I need to use many times, and I would prefer not to have to copy/paste the same code over and over again.
You can not declare function in if-statements.
you could do this:
<?php
function some_function_name() {
// do something here
}
if( a == b && c == d ) {
some_function_name();
}
?>
I would avoid defining the function inside a conditional if()
statement. Define the function first, at the top of the file and call it when necessary.
If you have a bunch of steps you want to put into function, you have to define function outside the if statements, preferably at the beginning or end of file, or maybe in a seperate file
If this function is a legitimate part of your workflow that will be used from multiple places, make it a top-level function (or a class method if applicable).
In the (relatively infrequent) case that you want to create a function to be passed as a callback, and this function's behavior is mostly to be determined by the values of variables, you can define an anonymous function:
$func = function() {
// do something here
}
if(c == d){
// you can call it like this, but read the above paragraph
$func();
}
Anonymous functions require PHP >= 5.3; if you are using an earlier version you can achieve the same result with create_function
, but it's such a hassle that it rarely is worth the trouble.
It's not a good practice, in fact, there is no reason for not defining the function outside the if block. The approach is very error prone.
You are getting the error because some_function_name()
bound to the scope of the first if block.
I want to create a function, because I have a bunch of steps which I need to use many times, and I would prefer not to have to copy/paste the same code over and over again.
You shouldn't copy/paste! That's what functions are for. Create your functions and reuse them as much as you want.
精彩评论