Using temporary variables when calling a function in PHP

Often I have seen functions called as

$content = getContent($isAdmin = false) 

While the function declaration is similar to

 function getContent($isAdmin = true){ ....} 

Why would someone add an overload to create a variable and use it only once in a function call!

I understand that this makes the function call understandable, but shouldn't PHPDoc blocks be used instead?

+8
variables php
source share
2 answers

I have a feeling that you are deeply shocked by such a "waste."

Keep cool using variables, nothing wrong, you should use them often. They usually make your code more visual and even faster.

A more descriptive part is here, if you look at this line, you see which parameter it is, because now it has a name.

but shouldn't PHPDoc blocks be used instead?

Well, actually this is not related to the comments (docblock). Even in the function definition there are no comments for this parameter:

 function getContent($isAdmin = true) { 

It is simply a definition of a parameter by its name. Also the docblock parameter would only be when you define the function:

 ... * @param $isAdmin bool (optional) true or false, true by default ... function getContent($isAdmin = true) { 

However, this is not the place where the function is called:

 $content = getContent($isAdmin = false) 

So, if you look at this line (and before pressing any hotkey or mouse button), you have already read this. Nothing needed, just code. It works even in notepad or not configured gedit.

 $nonAdmin = false; $content = getContent($nonAdmin); 

And btw, if your code needs comments, it's usually a sign that it's too complex. Also, the parameter name is much more important than docblock. A good name usually means that you don't need to have a docblock tag for it (this means: less code to support), because the name speaks for itself.

Also, modern IDEs know the type of parameter by static analysis, so you also do not need the docblock tag. No, you should not always use PHPDoc blocks.

+7
source share

Spelling

 $content = getContent($isAdmin = false) 

allows $isAdmin define even the outer scope, i.e. if you issue var_dump($isAdmin) , you get bool(false) .

This way you save the var assignment:

 $isAdmin = false; $content = getContent($isAdmin); ... someStuff($isAdmin); 
+3
source share

All Articles