Jump to content
Larry Ullman's Book Forums

Passing A Variable To Multiple Functions In One Line Or Several Lines


Recommended Posts

The variable $var is passed through 3 functions below:

1. mysqli_real_escape_string()

2. trim()

3. strtolower()

 

Example 1 passes $var through nested functions:

 

$var = mysqli_real_escape_string($dbc, trim(strtolower($_POST['hello_world'])));

 

 

Example 2 uses step by step method of passing the $var to the 3 functions:

 

$var = mysqli_real_escape_string($dbc, $_POST['helloworld']);

$var = trim($var);

$var = strtolower($var);

 

 

I'm not even sure if Example 2 might have problems, or if any of you had any instances where this method didn't work. My concern with Example 1 is that what if I had about 5 functions to pass $var too, it would be a really long nested line. I know also I can create a custom function containing the 5 functions, but in some cases it's not necessary.

 

Any advice appreciated

 

Thanks,

Mark

Link to comment
Share on other sites

This is mostly a matter of preference. I do agree that even applying $var to three functions in one line borders on being hard to read. Your ex 2 is just as good, although it technical calls the functions in the inverse order (not that it'd make a difference here).

Link to comment
Share on other sites

thanks larry, interesting that it goes in inverse order. I had done this to a variable a long time ago (before getting my hands on your book), and it was giving strange results. But it maybe because of the inverse order in the way I was passing the functions.

Link to comment
Share on other sites

Could be. If you think about it, the argument passed to the first (outer) function is that returned by the second (first inner) function. And that value is dependent upon the value returned by the third (innermost) function. So the processing of the variable goes from the innermost to the outermost functions.

Link to comment
Share on other sites

 Share

×
×
  • Create New...