Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting PHP functions within PHP functions within PHP functions. Bad Practice?

Is there a principle that advises against doing things like:

mysql_real_escape_string(trim(str_replace($var, "black", "<body text='%body%'>")));

If something like that should be a no-no, then would this be acceptable?

$var = trim($var);
$var = str_replace($var, "black", "<body text='%body%'>");
$var = mysql_real_escape_string($var);

Or is that bad practice also, to call and perform on the same variable on a single like, like I did above? Would it be better to do:

$var1 = trim($var);
$var2 = str_replace($var1, "black", "<body text='%body%'>");
$var3 = mysql_real_escape_string($var2);

I've always wondered this!

like image 536
Norse Avatar asked Dec 20 '25 05:12

Norse


2 Answers

I think the normal practice is to "nest" the functions like the first example.

There are a couple reasons, but mostly it shows that everything is happening to the same object in a specific order, with nothing going on in-between.

That being said, if you don't know exactly what you are going to be doing, you might want to start with the second example, so you can easily go back and add in functions.

Basically, the first is preferred and more common (I think) in the end, the second is good for testing and development, and the third is just a waste of resources (granted it is small, but there's no need).

like image 101
Jon Egeland Avatar answered Dec 22 '25 20:12

Jon Egeland


Nesting functions is fine - as long as you take readability into account. In this fairly simple example there's a great deal of mental effort that needs to be put into parsing the statement:

mysql_real_escape_string(trim(str_replace($var, "black", "<body text='%body%'>")));

If you decide to use nested functions, also make use of intelligent indentation to make it easier to see what's going on:

mysql_real_escape_string(
  trim(
    str_replace(
       $var, 
       "black", 
       "<body text='%body%'>"
)));
  • Each function argument is on it's own indented line (trim and str_replace are both being used as function arguments, as are $var, "black" and "<body text='%body%'>")
  • The ending ))); clearly delimits where the function nesting ends. It also provides a quick syntax checksum (count the number of opening parentheses and make sure they match the number of closing parentheses at te end).
like image 33
leepowers Avatar answered Dec 22 '25 20:12

leepowers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!