Understanding parameters and arguments in functions

Asked

Viewed 759 times

2

I am learning programming and I know that there are some answers on this topic, that have made me (theoretically) understand who is the parameter and who is the argument, however still do not understand the following:

If I can do it:

<?php
function funcParm(){
    $foo = "parâmetro";
    echo "$foo";
}
funcParm();
?>

Why do this?

<?php
function funcParm2($foo){
    echo "$foo";
}
funcParm("parâmetro");
?>

And yet how these parameters relate to each other in multiple nested functions?

In this example below my real question would be answered through a table test, but not to seem precious, if possible some information that indicates to me the relation of the parameters and arguments of the functions so I can perform the test.

function send(name) {
    // Local variable 'name' is stored in the closure
    // for the inner function.
    return function () {
        sendHi(name);
    }
}

function sendHi(msg) {
    console.log('Hello ' + msg);
}

var func = send('Bill');
func();
// Output:
// Hello Bill
sendHi('Pete');
// Output:
// Hello Pete
func();
// Output:
// Hello Bill

  • Is there anything else you think needs to improve the answers?

2 answers

4


Understand that you will only create a function if necessary, that is if the function is executed more than once (this is a more common scenario example, there are others), the argument is if the value is dynamic, will only do this probably if the value is fixed:

function funcParm(){
    $foo = "parâmetro";
    echo "$foo";
}
funcParm();

And will do so if the value is dynamic:

function funcParm2($foo){
    echo "$foo";
}
funcParm("foo");
funcParm("bar");
funcParm("baz");

I can assume that parameters and arguments in functions or methods are the same thing and this $foo = "parâmetro"; is not a parameter in fact, but is a variable.

Javascript unlike PHP, can work multiple scopes, ie when you do this:

function send(name) {
    // Local variable 'name' is stored in the closure
    // for the inner function.
    return function () {
        sendHi(name);
    }
}

The argument name rattlesnake for its anonymous function that is within return, this is because Javascript works like this, another example to understand how the scope works in Javascript, would be this:

function foo(a) {
   var b = 2;

   function bar() {
       //Consegue pegar o valor de foo
       console.log("função bar:", a, b);
   };

   var baz = function() {
       //Consegue pegar o valor de foo
       console.log("função anonima setada na variavel baz:", a, b);
   };

   bar();
   baz();

   return function() {
       //Consegue pegar o valor de foo
       console.log("função anonima no retorno da função foo():", a, b);
   };
}

(foo(2017))();

See that all written functions within of foo can access the variables.

In PHP the only way to do this is to use global $variavel; (which exposes to all places a variable), constant with define('<nome>', '<valor>');, use a superglobal or simply use the use:

function send($name) {
    return function () use ($name) {
        sendHi($name);
    }
}

As I explained here: /a/172134/3635

References

In Javascript parameters (arguments) are passed as values, ie if you do this it will return undefined:

function foobar(valor)
{
   setTimeout(function () {
       console.log(valor);
   }, 10);
}

var var1, var2;

foobar(var1);
foobar(var2);

var1 = 1000;
var2 = 2000;

But if you pass an object it will receive as "reference":

function foobar(valor)
{
   setTimeout(function () {
       console.log(valor.name);
   }, 10);
}

var var1 = {}, var2 = {};

foobar(var1);
foobar(var2);

var1.name = 1000;
var2.name = 2000;

In PHP to use references you can pass an object (a class for example) or use the & (And commercial), thus:

function foo(&$referencia) {
    $referencia *= 1002;
}

$valorinicial = 2;

foo($valorinicial);

//Note que aqui o valor foi alterado (saída será 2004)
echo $valorinicial;

See an online example: http://ideone.com/FQMPvi

3

When does

function funcParm() {
    $foo = "parâmetro";
    echo "$foo";
}

in practice is making a procedure and not a function, despite being declared so.

Why have a procedure?

Avoid code repeats, or at least organize a set of instructions contained in a single place giving a name to it. How this name can refer to it at some point in the code by name and what is inside will be executed.

The utility is reduced if it will use only once, but it can still be useful to give a separate responsibility, better document that those instructions are part of one thing only. In such abstract examples it is not always clear that.

If you are going to use more than once the same code there is the obvious advantage of not having to repeat what has already been written and you may be doing something more DRY, which is a desirable feature of fancy code.

The big difference for a function is that the latter should return a value. It’s okay to call it a function, everyone understands, but formally it’s not quite a function.

Note that in the example the variable is totally unnecessary. Anyway it is local, it is not a parameter, its value is known within the procedure and although it can vary, it will only do it inside it, it will not have a value that comes from outside.

What is to parametrize?

There are cases that each time you call a procedure, you want that set of instructions to be executed, but a small portion of the code is a little different. That is, there is a gap in it that must be filled in each run. It is a part variable of the code, precisely because it varies in each call. Even more, when you call the procedure will tell which is this variable part. So what we do is parameterize the function.

Parameter is just a variable that will define something.

pa râ me tro (for- + meter) male noun

  1. [Geometry] Constant line that enters the equation or construction of a curve, and serves as a fixed measure to compare the ordinates and the abscissas..

  2. Feature or variable that lets you define or compare something.

"parameter", in Dicionário Priberam da Língua Portuguesa [online], 2008-2013, https://www.priberam.pt/dlpo/par%C3%A2metro [consulted in 05-01-2017].

Then when calling the procedure an argument is passed, which is a value that will be assigned to the variable that serves as parameter. To help those who are coming here and don’t know What is the difference between parameter and argument?.

This gives flexibility in code usage. This example above will always print the same thing. Now:

function funcParm2($foo) {
    echo "$foo";
}
funcParm("parâmetro");

is printing this text in this example. Call yourself as:

funcParm("outra coisa");

will print "something else" literally :) Now this procedure is more useful because it serves to solve the same problem with different information on each call whenever necessary.

Javascript example

function send(name) { //recebe um parâmetro que não deixa de ser uma variável
    return function() { //ainda estamos dentro da outra função
        sendHi(name); //aquela variável é acessível aqui
    }
}
//este é um caso diferente é uma variável que se mantêm dentro do escopo

function sendHi(msg) {
    console.log('Hello ' + msg);
}

var func = send('Bill'); //aqui a variável recebe como valor uma função
func(); //chama a variável como a função
sendHi('Pete'); // //chama diretamente a outra função
func();

I put in the Github for future reference.

Here is a matter of life span and time, I will not repeat here what is already there, but the variable exists within the whole function, if it has a function within it, the variable continues to exist inside, because it has not left the most external function.

Being a parameter or a local variable doesn’t change anything. Maybe you’re asking two questions in a . I think here you want to know more how an anonymous function works. See also How Closures work in Javascript?. What about the Hoisting.

Completion

Parameter is a variable that will receive a value during the "function" call, so something will vary during execution.

Obviously this example does not help to understand so much the use of procedures (or even functions). Exchanging one simple execution for another brings little advantage, but can even bring. Then it comes to the subject of abstraction that I think does not fit here. The question is interesting because most programmers know how to create a function/procedure, but they don’t really know what it’s for, and when it’s useful or not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.