Introduction to functions in PHP

Lecture



Now that you are already familiar with variables, operations on them, you have become familiar with the control structures of the language, you can talk about functions.
There are situations where you repeat a sequence of instructions many times. And this sequence eventually accomplishes something completely complete.
A function is a bunch of actions. It takes arguments, does some operations with them, and returns the result. For example, Cooking pizza is a function that takes parameters - dough, eggs, cheese, ketchup, anchovies, a stove, and returns Pizza.
The return value of functions can be of any data type.
Another advantage of the functions is to simplify the reading of the program code.


Syntax

function имя(аргументы)
{
// тело функции;
}

The name of the function may consist of Latin letters, numbers and underscores. It should not start with a digit. Everything is exactly the same as with the names of variables.
You may have noticed that already from the first lesson we confuse you with the concepts parameter and argument
Arguments are unspecified incoming data.
The parameters are known data.
Those. when we describe a function, in parentheses are arguments, when we call - parameters. But sticking to this, I think, is not necessary.
In the function that prepares the pizza - the argument will be "the number of required dishes" and the parameter will be the number 5. In any case, in all cases we are talking about the data passed to the function. Consider creating a homemade function using an example.
The task of the function is to find the largest element of the array.

<?PHP
function arr_max($arr) // Определяем функцию arr_max принимающую один аргумент
{
// Входящие данные: Массив
// Исходящие данные: значение элемента в массиве.

// Устанавливаем значение нулевого элемента как максимального
$max = $arr[0];

for ($i = 1; isset($arr[$i]); $i++) // для каждого элемента массива
if ($arr[$i] > $max) // проверяем что больше. Текущее значение или максимум
$max = $arr[$i]; // Если максимум больше, то меняем максимум на новый

$arr[1] = 95; // Поменяем значение первого элемента массива. Не задумывайтесь почему. Чуть позже увидите.

// функция возвращает результат.
// Результат в данном случае самое большое число в массиве
return $max;
}

// Закончилось определение функции. Дальше продолжение скрипта.


$ar1 = array(4, 6, 12, 9, '5', 23);
$ar2 = 'dabcjfutZfgh';

echo arr_max($ar1)."<br>\n"; // Выведет 23

echo '$ar1[1]'.$ar1[1]; // выведет 6 (а не 95, помните ту загадочную строку функции?). Получается значение не изменилось
// Напомним: в одинарных кавычках значения переменных не подставляются

// подумайте над результатами такого вызова:
echo arr_max($ar2);
?>


Area of ​​visibility

How is it that the assignment operation $ arr [1] = 95 did not change the value of the variable outside the function?

There is such a concept - Scope. To understand this concept is easy and understandable =)
The function is a kind of small subroutine.
This subroutine has its own variables, and it simply does not see the variables from the main program.

Since in this program from one of the parameters entered the array $ arr [1]. This means that the function saw it completely and could work with it. But in fact, the function is passed to the variable, and its exact copy. Its value. Therefore, when our subroutine completes its execution, all its variables (copies of ours) are deleted.


Passing parameters by reference

Let me remind you a little of the first lesson in which I explained how a computer stores data in memory, and that $ variable actually stores not the value at all, but the cell ID in the memory in which our value is located.

As you noted in the example above, all variables used in functions are local, that is, created and deleted are used in the function itself, and beyond its limits are not accessible.

In order to pass into the function not the value of the variable, but the variable itself which the function can change and outside of it we can use it - there is a special way of passing parameters - By reference. The function call with the parameters by reference appears with the addition of the & character like this: myFunction (& $ myvar);

When in a function call, a variable is passed by reference, the cell ID is passed, not the value. When you call the func ($ a) function, the interpreter first gets the value of the $ a variable from memory and passes that value to the function. After that, a new variable is created in the function itself, which is assigned this value.

When a function is called with a parameter by reference to the func (& $ a), the interpreter passes to the function not the value of the variable, but the identifier of the cell in memory. When a function is called with parameters in the usual way, all changes occur in another, new memory cell and outside the function, work continues with the old cell. And when passing by reference, all changes occur in the same cell and therefore changes are visible from outside the function itself.


Operator return

Our function is not required to return anything with a return construct.
Perhaps she just performs a series of operations, for example,
output several lines or something else.
For example, the code already familiar to us from the previous chapter can be formatted as follows:

<?PHP
function who_is_it($sName)
{
if($sName=="EuGen") echo("Да, это я");
elseif($sName=="Valenok") echo("Теперь я точно уверен, это Valenok");
elseif($sName=="Champion") echo("Это тоже наш автор, Champion");
else echo("Я запутался..");
}
// основная программа
$val = 'Valenok'; who_is_it($val);
$eu = 'EuGen'; who_is_it($eu);
$ch = 'Champion'; who_is_it($ch);
$unknown = 'Гость'; who_is_it($unknown);
?>

We did not ask the function to return anything. In this case, the interpreter returns a Null value.

But it happens that one of the returned value is not enough. It is also possible that you want changes in variables in the function to be reflected in the main program.

To do this, you can use two solutions.
Either make our subroutine see the variable from the outside, or transfer the original parameter to it instead of a copy.

Putting the & in front of the variable, we indicate the interpreter that we are passing
not the variable itself, but a reference to the variable. In fact, this can be understood as a type Resource.
The function will not work with a copy of data in memory, but directly with a specific cell in memory. Thus, all changes will be recorded straight.
in the required area of ​​RAM and changes will be saved.

Let the function return the sum of 2 terms, the product will be written to the first parameter, and the second parameter will simply double.

<?PHP
function func(&$var1, &$var2)
{
$res = $var1 + $var2;
$var2 = $var2 * 2;
$var1 = $var1 * $var2;
return $res;
}
$a = 3;
$b = 4;
echo func($a, $b); // 7
echo $a; // 12
echo $b; //8
?>

The global construct allows functions to see and use a variable from the outside world.
In this case, do not even have to pass her the parameters, as she sees them herself.

<?PHP
function func()
{
global $var1, $var2;
$res = $var1 + $var2;
$var2 = $var2 * 2;
$var1 = $var1 * $var2;
return $res
}
$var1 = 3;
$var2 = 4;
echo func(); // 7
echo $var1; // 12
echo $var2; //8
?>


Recursion

Let's take a function that is looking for some element of the Fibonacci series (0,1,1,2,3,5,8 ... - the first two elements are 0 and 1, the rest are the sum of the two previous ones). Let's write it without recursion, because we don’t know what it is yet.

<?PHP
function fibonacci($num) // $num - номер интересующего нас элемента
{
if ($num < 1) { // номера элемента меньше 1 не существует, заканчиваем функцию
return false;
}
if ($num <= 2) { // если это один из первых элементов, нетрудно увидеть как они определяются
return ($num - 1);
}

// общий случай. Идем от 3го до требуемого номера
$pre_pre = 0; // элемент, скажем так, предпредыдущий.
$current = 1; // текущий
for ($i = 3; $i <= $num; $i++) {
$pre = $current; // бывший текущий становится предыдущим
$current = $pre + $pre_pre; // определяем текущий элемент
$pre_pre = $pre; // бывший предыдущий становится предпредыдущим
}
return $current;
}

/*** Основная часть программы ***/
$n = 5;
echo fibonacci($n); // 0,1,1,2,3 - получается 3
?>

The function is quite large. Let's look at it and see that a loop is used in this function. The cycle has an exit condition and in each iteration we work with the values ​​that remained after the previous iteration. Then it is convenient to use recursion. A function is called recursive if it calls itself. Here is how! Let's rewrite that function using recursion.

<?PHP
// $pre и $pre_pre, как и в тот раз - предыдущий и предпредыдущий элемент.
// $n номер элемента, который мы ищем, НО реально смысл в этой переменной несколько другой.
// Она хранит в себе количество элементов, которое осталось посчитать
// Считать сумму начинаем с 3го элемента.
function fib($n, $pre = 1, $pre_pre = 0)
{
if ($n == 1) return 1;
if ($n < 1) return false;
if ($n == 2) // начинали с 3го, поэтому выходим, когда осталось посчитать два.
return $pre;

return fib($n - 1, $pre + $pre_pre, $pre);
}


echo fib(5);
?>

As you can see, there are far fewer lines.

But recursion is used not only instead of cycles. This is done infrequently, because usually the cycle is easier. There are tasks that can not be solved without recursion. For example, building a tree of files and subdirectories in the directory. Using recursion, we would write a function with the name of the folder as an input parameter. This function takes an element and, if it is a file, simply displays its name, but if it is a directory, the function calls itself for that directory. When you learn the functions of working with the file system, you will write it)
How to implement it without recursion ... I find it difficult to think.

When describing recursive functions, it is necessary to provide a condition for exiting the function so that it is not infinite. Like the loop.

Yes, by the way, see that the parameters of function 3, and I called it in the program with one parameter? Notice that when declaring a function, the last two parameters are declared as follows: $ variable = value . They are given a default value. Those. it is not necessary to pass these parameters when calling, unless, of course, they differ from the default values. If different, you must pass. You can also pass only one of these parameters, you can do everything. But if you don’t pass all the parameters, how does php determine which variables you meant? Very simple left to right. If less values ​​are provided than functions need, the rightmost variables will accept the default value.

Now questions on the chapter!

1. In which variant (s) is the function declared syntactically incorrect? Why?

  • function my_func () {}
  • function _qwerty ($ a) {}
  • function 4func ($ a = 4) {}
  • function func ($ a = 4) {}
  • function func.my ($ a) {}
  • function func-my ($ a = 4) {}
  • function int ($ a = 4) {}
  • function return ($ a = 4) {}

2. In which variant is the function func ($ a, $ b = 4, & $ c, $ d = 5, $ e = 6) called incorrectly? Why? (all variables have a value, the function returns a value)

  • call func (1, 3, $ d)
  • $ d = func (1, 3, 5)
  • $ d = func (1, 3, $ f, 6)
  • echo func ($ s)
  • func (1, func (1, 3, $ d), $ d)
  • func (1, $ d, func (1, 3, $ d))

3. Write a function that looks for the minimum of the array and its index so that you can work with the index and with the minimum itself in the main program.

4. Write the recursive factorial function.

LESSON number 3. Introduction to the functions.
1. In which variant (s) is the function declared syntactically incorrect? Why?
-a- function my_func () {} - right, all without a trick
-b- function _qwerty ($ a) {} - also true
-c- function 4func ($ a = 4) {} - starts with a digit, which is wrong
-d- function func ($ a = 4) {} is true
-e- function func.my ($ a) {} - the name of the function contains a dot - incorrect
-f- function func-my ($ a = 4) {} - the name of the function contains a minus (or dash - it does not matter) - wrong
-g- function int ($ a = 4) {} - int - reserved word, however, such a function declaration is syntactically correct and it will work
-h- function return ($ a = 4) {} - return is also a reserved word, but it is an operator. Therefore, the function cannot be declared this way.

2. In which variant is the function func ($ a, $ b = 4, & $ c, $ d = 5, $ e = 6) called incorrectly? Why? (all variables have a value, the function returns a value)
-a- call func (1, 3, $ d) - wrong
-b- $ d = func (1, 3, 5) is wrong , because the third parameter must be passed by reference, i.e. it should be a variable, not a constant.
-c- $ d = func (1, 3, $ f, 6) - true
-d- echo func ($ s) is wrong. Not all other parameters have default values.
-e- func (1, func (1, 3, $ d), $ d) is correct.
-f- func (1, $ d, func (1, 3, $ d)) is incorrect for the same reason as in b. Under the link the variable should be transferred
created: 2016-01-25
updated: 2021-03-13
132401



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)