Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using temporary variables while calling function in PHP

Tags:

variables

php

Often, I have seen functions being called like

$content = getContent($isAdmin = false)

Whereas the function declaration is like

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

Why would anyone add a overload of creating a variable and using it only once in a function call !!

I understand that this makes the function call clear, but shouldn't we use PHPDoc blocks instead?

like image 761
Akash Avatar asked Oct 07 '12 18:10

Akash


People also ask

How do you call a variable inside a function in PHP?

If you wish to use a PHP global variable inside a certain function, you should use the keyword global in front of the variable. In the example below you can see how PHP variables $x and $y are used inside a function called learnTest() . <?

How can you pass a local variable to an anonymous function in PHP?

Yes, use a closure: functionName($someArgument, function() use(&$variable) { $variable = "something"; }); Note that in order for you to be able to modify $variable and retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using & . It's new!


1 Answers

I have the feeling that you are deeply shocked by so much "waste".

Keep cool, using variables is nothing bad, you should use them often. They normally make your code more descriptive and even faster.

The more descriptive part is the case here, if you look at that line, you see which parameter that is because now it has a name.

but shouldn't we use PHPDoc blocks instead?

Well, actually this is unrelated to (docblock) comments. Even in the function definition, there is no comment for that parameter:

function getContent($isAdmin = true) {

It's just the definition of the parameter by it's name. Also the docblock parameter would be only when you define the function:

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

However that is not where the function is called:

$content = getContent($isAdmin = false)

So if you look at that line (and before pressing any hotkey or mouse button), you already read that. Nothing needed, only the code. Works even in notepad or an non-configured gedit.

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

And btw, if your code needs comments, this is normally a sign that it is too complicated. Also the name of a parameter is much more important than it's docblock. A good name normally means that you do not need to have a docblock tag for it (that means: less code to maintain), because the name speaks for itself.

Also modern IDEs know the type of the parameter by static analysis and therefore you do not need the docblock tag either. So no, you do not just should always use PHPDocblocks.

like image 67
hakre Avatar answered Oct 16 '22 09:10

hakre