diff --git a/modules/35-calling-functions/135-calling-functions-default-params/en/README.md b/modules/35-calling-functions/135-calling-functions-default-params/en/README.md index db5bafd5..83dec06d 100644 --- a/modules/35-calling-functions/135-calling-functions-default-params/en/README.md +++ b/modules/35-calling-functions/135-calling-functions-default-params/en/README.md @@ -36,28 +36,89 @@ round(10.25) → arguments: 10.25, (0) → 10 └── default value ``` -The number of optional parameters depends on the specific function, but required ones always come before optional ones. +In the signature of `round()`, the required parameter `$num` comes before the optional `$precision`. Another function may have a different number of parameters and different default values. -## A function's signature +## How to read a function's documentation -Every function has a **signature** that contains a description of its name, its parameters, and the order in which they are used. The signature helps you understand what data the function expects and what will happen if the parameters are not specified. +Documentation describes what data a function accepts and what result it returns. Each function has its own page in the [PHP manual](https://www.php.net/manual/en/). Below is a fragment of the [reference for `round()`](https://www.php.net/manual/en/function.round.php), with part of the text omitted. -Let's look at the [documentation](https://www.php.net/manual/en/function.round.php) for the `round()` function. If we simplify it a little, the signature looks like this: +```text +Description + +round(int|float $num, int $precision = 0, int|RoundingMode $mode = RoundingMode::HalfAwayFromZero): float + +Returns the rounded value of num to specified precision +(number of digits after the decimal point). +... + +Parameters + +num + The value to round. +precision + The optional number of decimal digits to round to. + ... +mode + ... + +Return Values + +The value rounded to the given precision as a float. +``` + +Read the page from top to bottom, step by step. + +1. The Description section starts with the signature, which shows the function name, the parameters in order, and the result type. +2. The first sentence briefly says what the function does. +3. The Parameters section explains each parameter by its name from the signature. You can skip long explanations and tables of modes on a first read. +4. The Return Values section describes the result. Here the function returns a `float` even when it rounds to an integer. + +The last parameter, `$mode`, controls the rounding mode. It is rarely needed, so we won't consider it for now. Without it, the signature looks like this. ```php round(int|float $num, int $precision = 0): float ``` -The function is called `round`. The `$num` parameter is required — it takes the number to round (an integer or a fraction). The `$precision` parameter has the default value `0`, that is, it is optional; if you don't specify it, the number will be rounded to an integer. After the colon comes the type of the result — the function returns a fractional number (`float`). +The names `$num` and `$precision` stand for parameters. In a call you put concrete values in their place, for example `round(10.25, 1)`. Each name is preceded by the type of value the function expects. + +The table matches the parts of the signature to the arguments of this call. + +| Part of the signature | What it means | In the call `round(10.25, 1)` | +| --- | --- | --- | +| `round` | Function name | We call `round()` | +| `int\|float $num` | Required parameter, an integer or a fraction to round | We pass `10.25` | +| `int $precision = 0` | Optional parameter, an integer with the default value `0` | We pass `1` instead of the default value | +| `: float` | Result type | We get a fractional number | + +The `=` sign in `$precision = 0` marks the default value. This notation tells you the second argument can be omitted. The Parameters section explains how the function uses that `0`. For `round()`, precision `0` means rounding to an integer. + +Let's check both cases in the [interactive PHP console](https://psysh.org/). You don't type the `` sign marks the input line, and the console prints the result under each call after the `=` sign. + +```console +> round(10.25, 1) += 10.3 +> round(10.25) += 10.0 +``` + +The first call passes the precision `1` and gets the number `10.3`. The second leaves `$precision` at its default and gets `10.0`. The console shows the decimal part because the result has the `float` type, as the Return Values section promises. This is how we match the signature, the explanation in the documentation, and the actual result. + +## Notation in references + +A signature contains auxiliary marks. They help you read the signature and are not passed to the function in a call. + +| Notation in the reference | How to read it | +| --- | --- | +| `int $precision = 0` | `$precision` has a default value, the argument can be omitted | +| `int\|float $num` | The parameter accepts a value of any of the listed types | +| `round(float $val [, int $precision = 0])` | This is how some third-party references and articles mark optional arguments. The square brackets are not part of the call | -The full signature from the documentation has one more optional parameter that controls the rounding mode. It is rarely needed, so we won't consider it for now. +For example, the notation `int|float $num` describes a single parameter. The call `round(7)` passes it the integer `7` and returns `7.0`. Neither the type, nor the name `$num`, nor the `|` sign go into the call. -## How to work with new functions +If your browser translates the page, check function names, parameter names, and symbols in the signature against the original. Code uses the original names from the documentation. -When you come across a new function, you can use a simple pattern: +## Working with an unfamiliar function -1. Open the documentation and find the function's signature. -2. Look at usage examples. -3. Go to the interactive PHP shell (it is launched with the `php -a` command) and try calling the function with different arguments. +Reading a reference starts with a task. For example, to round a price to one decimal place, we find the number and the precision in the signature of `round()`, check what precision means in the parameter list, and then try the call `round(10.25, 1)`. If the result matches the description, the call can go into the program. -This approach helps you quickly figure out how exactly a function works, which of its parameters are required and which are optional, and what results it returns. +Another function will have its own parameters and rules. Its signature tells us which arguments to pass, its description tells us the result and the limits, and a small example lets us check our understanding. diff --git a/modules/35-calling-functions/135-calling-functions-default-params/es/README.md b/modules/35-calling-functions/135-calling-functions-default-params/es/README.md index 1a2a97f1..735f0d20 100644 --- a/modules/35-calling-functions/135-calling-functions-default-params/es/README.md +++ b/modules/35-calling-functions/135-calling-functions-default-params/es/README.md @@ -36,28 +36,89 @@ round(10.25) → argumentos: 10.25, (0) → 10 └── valor por defecto ``` -La cantidad de parámetros opcionales depende de la función concreta, pero los obligatorios siempre van antes de los opcionales. +En la firma de `round()` el parámetro obligatorio `$num` va antes del opcional `$precision`. Otra función puede tener otra cantidad de parámetros y otros valores por defecto. -## La firma de una función +## Cómo leer la documentación de una función -Cada función tiene una **firma**, que contiene la descripción de su nombre, sus parámetros y el orden en que se usan. La firma ayuda a entender qué datos espera la función y qué ocurrirá si los parámetros no se indican. +La documentación describe qué datos recibe una función y qué resultado devuelve. Cada función tiene su propia página en el [manual de PHP](https://www.php.net/manual/es/). A continuación se muestra un fragmento de la [referencia de `round()`](https://www.php.net/manual/es/function.round.php), con parte del texto omitida. -Veamos la [documentación](https://www.php.net/manual/es/function.round.php) de la función `round()`. Si la simplificamos un poco, la firma se ve así: +```text +Descripción + +round(int|float $num, int $precision = 0, int|RoundingMode $mode = RoundingMode::HalfAwayFromZero): float + +Devuelve el valor redondeado de num a la precisión precision (número de +dígitos después del punto decimal). +... + +Parámetros + +num + El valor a redondear. +precision + El número opcional de decimales a redondear. + ... +mode + ... + +Valores devueltos + +El valor redondeado a la precision dada como float. +``` + +La página se lee de arriba abajo, paso a paso. + +1. La sección «Descripción» empieza con la firma, que indica el nombre de la función, los parámetros en orden y el tipo del resultado. +2. La primera frase dice brevemente qué hace la función. +3. La sección «Parámetros» explica cada parámetro por su nombre en la firma. Las explicaciones largas y las tablas de modos se pueden saltar en la primera lectura. +4. La sección «Valores devueltos» describe el resultado. Aquí la función devuelve un número de tipo `float`, incluso cuando redondea a entero. + +El último parámetro, `$mode`, controla el modo de redondeo. Se necesita pocas veces, por lo que de momento no lo analizamos. Sin él, la firma se ve así. ```php round(int|float $num, int $precision = 0): float ``` -La función se llama `round`. El parámetro `$num` es obligatorio: recibe el número que se va a redondear (entero o fraccionario). El parámetro `$precision` tiene el valor por defecto `0`, es decir, es opcional; si no se indica, el redondeo se hará al número entero. Después de los dos puntos se indica el tipo del resultado: la función devuelve un número fraccionario (`float`). +Los nombres `$num` y `$precision` designan parámetros. En la llamada se sustituyen por valores concretos, por ejemplo `round(10.25, 1)`. Delante de cada nombre se indica el tipo del valor que espera la función. + +La tabla relaciona las partes de la firma con los argumentos de esa llamada. + +| Parte de la firma | Qué significa | En la llamada `round(10.25, 1)` | +| --- | --- | --- | +| `round` | Nombre de la función | Llamamos a `round()` | +| `int\|float $num` | Parámetro obligatorio, número entero o fraccionario que se redondea | Pasamos `10.25` | +| `int $precision = 0` | Parámetro opcional, número entero con valor por defecto `0` | Pasamos `1` en lugar del valor por defecto | +| `: float` | Tipo del resultado | Obtenemos un número fraccionario | + +El signo `=` en `$precision = 0` indica el valor por defecto. Esta notación muestra que el segundo argumento se puede omitir. Cómo usa la función ese `0` lo explica la sección «Parámetros». En `round()`, la precisión `0` significa redondear a un número entero. + +Comprobemos los dos casos en la [consola interactiva de PHP](https://psysh.org/). En la consola no se escribe la línea `` marca la línea de entrada, y debajo de cada llamada, después del signo `=`, la consola imprime el resultado. + +```console +> round(10.25, 1) += 10.3 +> round(10.25) += 10.0 +``` + +La primera llamada pasa la precisión `1` y obtiene el número `10.3`. La segunda deja `$precision` con su valor por defecto y obtiene `10.0`. La consola muestra la parte decimal porque el resultado es de tipo `float`, tal como indica la sección «Valores devueltos». Así relacionamos la firma, la explicación de la documentación y el resultado de la ejecución. + +## Notación en la referencia + +En la firma aparecen marcas auxiliares. Ayudan a leer la firma y no se pasan a la función en la llamada. + +| Notación en la referencia | Cómo leerla | +| --- | --- | +| `int $precision = 0` | `$precision` tiene valor por defecto, el argumento se puede omitir | +| `int\|float $num` | El parámetro acepta un valor de cualquiera de los tipos indicados | +| `round(float $val [, int $precision = 0])` | Así marcan los argumentos opcionales algunas referencias y artículos de terceros. Los corchetes no forman parte de la llamada | -En la firma completa de la documentación hay un parámetro opcional más, que controla el modo de redondeo. Se necesita pocas veces, por lo que de momento no lo analizamos. +Por ejemplo, la notación `int|float $num` describe un solo parámetro. La llamada `round(7)` le pasa el número entero `7` y devuelve `7.0`. Ni el tipo, ni el nombre `$num`, ni el signo `|` se copian en esa llamada. -## Cómo trabajar con funciones nuevas +Si el navegador traduce la página, hay que comparar los nombres de funciones y parámetros y los símbolos de la firma con el original. En la versión en español del manual las descripciones están traducidas, pero la firma sigue en inglés. En el código se usan los nombres originales de la documentación. -Cuando te encuentras con una función nueva, puedes usar un patrón sencillo: +## Trabajar con una función desconocida -1. Abrir la documentación y encontrar la firma de la función. -2. Mirar ejemplos de uso. -3. Pasar a la consola interactiva de PHP (se inicia con el comando `php -a`) y probar a llamar a la función con diferentes argumentos. +La lectura de la referencia empieza por la tarea. Por ejemplo, para redondear un precio a un decimal, en la firma de `round()` buscamos el número y la precisión, en la lista de parámetros comprobamos qué significa la precisión y después probamos la llamada `round(10.25, 1)`. Si el resultado coincide con la descripción, la llamada se puede usar en el programa. -Este enfoque ayuda a entender rápidamente cómo funciona exactamente la función, cuáles son sus parámetros obligatorios y opcionales, y qué resultados devuelve. +Otra función tendrá sus propios parámetros y reglas. Con su firma decidimos qué argumentos pasar, con la descripción conocemos el resultado y las limitaciones, y con un ejemplo pequeño comprobamos lo que hemos entendido. diff --git a/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md b/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md index 0963aec7..e8102e64 100644 --- a/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md +++ b/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md @@ -38,28 +38,92 @@ round(10.25) → аргументы: 10.25, (0) → 10 └── значение по умолчанию ``` -Количество необязательных параметров зависит от конкретной функции, но обязательные всегда идут перед необязательными. +В сигнатуре `round()` обязательный параметр `$num` стоит перед необязательным `$precision`. У другой функции количество параметров и их значения по умолчанию могут отличаться. -## Сигнатура функции +## Как читать документацию функции -У каждой функции есть **сигнатура**, содержащая описание ее имени, параметров и порядка их использования. Сигнатура помогает понять, какие данные функция ожидает и что будет происходить, если параметры не указаны. +Документация описывает, какие данные принимает функция и какой результат возвращает. У каждой функции в [руководстве PHP](https://www.php.net/manual/ru/) своя страница. Ниже приведён фрагмент [справки о `round()`](https://www.php.net/manual/ru/function.round.php), часть текста пропущена. -Посмотрим на [документацию](https://www.php.net/manual/ru/function.round.php) для функции `round()`. Если ее немного упростить, сигнатура выглядит так: +```text +Описание + +round(int|float $num, int $precision = 0, int|RoundingMode $mode = RoundingMode::HalfAwayFromZero): float + +Функция возвращает значение числа num, которое округлила с точностью +precision — количество цифр после запятой. +... + +Список параметров + +num + Значение, которое требуется округлить. +precision + Необязательное количество десятичных знаков, до которых функция + округлит число. + ... +mode + ... + +Возвращаемые значения + +Функция возвращает число с плавающей точкой (float), которое получила +путём округления входного числа до точности, которую установили +в параметре precision. +``` + +Страницу читают сверху вниз по шагам. + +1. Раздел «Описание» начинается с сигнатуры, где указаны имя функции, параметры по порядку и тип результата. +2. Первое предложение кратко говорит, что делает функция. +3. Раздел «Список параметров» объясняет каждый параметр по имени из сигнатуры. Длинные пояснения и таблицы режимов на первом чтении можно пропустить. +4. Раздел «Возвращаемые значения» описывает результат. Здесь функция возвращает число типа `float`, даже если округляет до целого. + +Последний параметр `$mode` управляет режимом округления. Он нужен редко, поэтому мы его пока не рассматриваем. Без него сигнатура выглядит так. ```php round(int|float $num, int $precision = 0): float ``` -Функция называется `round`. Параметр `$num` обязателен — он принимает число для округления (целое или дробное). Параметр `$precision` имеет значение по умолчанию `0`, то есть необязателен; если его не указать, округление произойдет до целого числа. После двоеточия указан тип результата — функция возвращает дробное число (`float`). +Имена `$num` и `$precision` обозначают параметры. При вызове на их места подставляются конкретные значения, например `round(10.25, 1)`. Перед каждым именем указан тип значения, которое ожидает функция. + +В таблице сопоставлены части сигнатуры и аргументы этого вызова. + +| Часть сигнатуры | Что она означает | В вызове `round(10.25, 1)` | +| --- | --- | --- | +| `round` | Имя функции | Вызываем `round()` | +| `int\|float $num` | Обязательный параметр, целое или дробное число для округления | Передаём `10.25` | +| `int $precision = 0` | Необязательный параметр, целое число со значением по умолчанию `0` | Передаём `1` вместо значения по умолчанию | +| `: float` | Тип результата | Получаем дробное число | + +Знак `=` в `$precision = 0` сообщает о значении по умолчанию. Из этой записи видно, что второй аргумент можно пропустить. Как именно функция использует `0`, объясняет раздел «Список параметров». У `round()` точность `0` означает округление до целого числа. + +Проверим оба случая в [интерактивной консоли PHP](https://psysh.org/). Строку `` обозначает строку ввода, а под вызовом после знака `=` консоль печатает результат. + +```console +> round(10.25, 1) += 10.3 +> round(10.25) += 10.0 +``` + +Здесь первый вызов передаёт точность `1` и получает число `10.3`. Второй оставляет `$precision` по умолчанию и получает `10.0`. Консоль показывает дробную часть, потому что результат имеет тип `float`, как и обещает раздел «Возвращаемые значения». Так мы сопоставляем сигнатуру, объяснение в документации и результат выполнения. + +## Обозначения в справке + +В сигнатуре встречаются служебные обозначения. Они помогают прочитать сигнатуру и при вызове в функцию не передаются. + +| Запись в справке | Как её читать | +| --- | --- | +| `int $precision = 0` | У `$precision` есть значение по умолчанию, аргумент можно пропустить | +| `int\|float $num` | Параметр принимает значение любого из перечисленных типов | +| `round(float $val [, int $precision = 0])` | Так необязательные аргументы обозначают в сторонних справочниках и статьях. Квадратные скобки не входят в вызов | -В полной сигнатуре из документации есть еще один необязательный параметр, который управляет режимом округления. Он нужен редко, поэтому мы его пока не рассматриваем. +Например, запись `int|float $num` описывает один параметр. Вызов `round(7)` передаёт ему целое число `7` и возвращает `7.0`. Ни тип, ни имя `$num`, ни знак `|` в такой вызов не копируются. -## Как работать с новыми функциями +Если браузер переводит страницу, имена функций, параметров и символы в сигнатуре нужно сверять с оригиналом. На русской версии руководства описания переведены, а сигнатура остаётся на английском. В коде используются исходные имена из документации. -Когда вы встречаете новую функцию, можно использовать простой паттерн: +## Работа с незнакомой функцией -1. Открыть документацию и найти сигнатуру функции. -2. Посмотреть примеры использования. -3. Перейти в интерактивную оболочку PHP (она запускается командой `php -a`) и попробовать вызвать функцию с разными аргументами. +Чтение справки начинается с задачи. Например, для округления цены до одного знака после запятой в сигнатуре `round()` находим число и точность, в списке параметров проверяем смысл точности, затем пробуем вызов `round(10.25, 1)`. Если результат соответствует описанию, этот вызов можно использовать в программе. -Такой подход помогает быстро разобраться, как именно работает функция, какие у нее обязательные и необязательные параметры и какие результаты она возвращает. +У другой функции будут свои параметры и правила. По её сигнатуре мы определяем, какие аргументы передать, по описанию узнаём результат и ограничения, а на небольшом примере проверяем своё понимание.