Understanding parameters and arguments in functions

1

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

If I can do this:

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

Why do this?

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

And how do these parameters relate to multiple functions or nested functions?

In this example, my real question would be answered through a table test, but in order not to seem precious, if possible some information that indicates the relation of the parameters and arguments of the functions so that I can carry out 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
    
asked by anonymous 05.01.2017 / 17:01

2 answers

3

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

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

And will do this 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 and this $foo = "parâmetro"; is not a de facto parameter, but it is a variable.

JavaScript unlike PHP, you can work multiple scopes, that is 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 cascateia for its anonymous function that is inside return , this is because Javascript works like this, another example to understand how the scope works in Javascript, would 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 of foo can access variables.

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

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

As I explained here: link

References

In the 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 & (commercial E), like this:

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

$valorinicial = 2;

foo($valorinicial);

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

See an example online: link

    
05.01.2017 / 17:09
2

When you do

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

In practice you are doing a procedure rather than a function , although it is declared as such.

What is the reason for having a procedure?

Avoid repetitions or at least organize a set of instructions contained in a place giving a name to this. As this name may refer to it somewhere in the code by name and what is in there will be executed.

If it is to be used only once the utility is reduced, but it may still be useful to give a separate responsibility, to better document that those instructions are part of one thing. In abstract examples this is not always clear.

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

The big difference for a function is that it should return a value. No problem calling this a function, everyone understands, but formally it is not quite a function.

Note that in the example the variable is totally unnecessary. But 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 parameterization?

There are cases that every time you call it, want that set of instructions to be executed, but a small portion of it is a bit different. That is, there is a gap in it that must be fulfilled in each execution. It is a variable part of the code, precisely because it varies in each call. Moreover, when you call the procedure it will tell you what that variable part is. So what we do is parametrize the function.

Parameter is just a variable that will define something.

  

pa · râ 'me · tro (para- + -metro) masculine noun

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

  •   
  • Character or variable that allows you to define or compare something.

  •   

    "parameter", in Dictionary Priberam da Língua Portuguesa [online],   2008-2013, link [consulted at   05-01-2017].

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

    This gives you flexibility in using the code. This example above will always print the same thing. Already:

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

    You are printing this in this example. If you call 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 needed.

    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();

    Here is a question of scope and lifetime , I will not repeat here what is already there, but the variable exists inside the whole function, if it has a function inside it, the variable still exists inside because it did not leave the outer function.

    Being a parameter or a local variable does not change anything. Maybe you're asking two questions in one. I think here you want to know more how an anonymous function works . See also How Closures Work in JavaScript? . And about the hoisting .

    Conclusion

    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 you understand so much the use of procedures (or even functions). Exchanging a simple run for another brings little benefit. But you can even bring it. There you go into the matter of abstraction, which I think does not fit here. The question is interesting because most programmers know how to create a function / procedure, but are not sure what it actually works for, and when it's useful or not.

        
    05.01.2017 / 17:31