From 192ac2d9a66ee9f1d1a2e8576a6a6d04bb069be1 Mon Sep 17 00:00:00 2001 From: Nikolay Gagarinov Date: Thu, 5 Nov 2026 15:30:43 +0500 Subject: [PATCH 1/3] =?UTF-8?q?feat(functions):=20=D0=BE=D0=B1=D1=8A=D1=8F?= =?UTF-8?q?=D1=81=D0=BD=D0=B8=D1=82=D1=8C=20=D1=87=D1=82=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D0=B8=20PHP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: CONTENT-763 Co-Authored-By: Claude Opus 5.5 --- .../en/README.md | 59 +++++++++++++++---- .../es/README.md | 59 +++++++++++++++---- .../ru/README.md | 59 +++++++++++++++---- 3 files changed, 141 insertions(+), 36 deletions(-) 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..8451b684 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,63 @@ 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. A function's page in the [PHP manual](https://www.php.net/manual/en/) is split into sections. The Description section contains the signature, that is, the function's name, its parameters, and their order. The Parameters section explains what each parameter is for, and the Return Values section describes the result. You need all three sections to write a call. -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: +Let's look at the [reference for `round()`](https://www.php.net/manual/en/function.round.php). If we simplify it a little, 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 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. +The table matches the parts of the signature to the arguments of this call. -## How to work with new functions +| 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 | -When you come across a new function, you can use a simple pattern: +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. -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. +The Return Values section specifies the result. The `round()` reference says the function returns a floating-point number (`float`) rounded to the given precision. That's why the result stays a fractional number even when you round to an integer. -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. +The full signature in the documentation has one more optional parameter, `$mode`, which controls the rounding mode. It is rarely needed, so we won't consider it for now. + +Let's check both cases in the interactive PHP shell, which starts with the `php -a` command. The `php >` line is the shell prompt. The shell doesn't print results by itself, so we print them with the `var_dump()` function, which shows the type and the value. + +```console +php > var_dump(round(10.25, 1)); +float(10.3) +php > var_dump(round(10.25)); +float(10) +``` + +The first call passes the precision `1` and gets the number `10.3`. The second leaves `$precision` at its default and gets `10` of type `float`, 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 | +| `?string $decimal_separator` | The `?` sign allows passing `null` instead of a string | +| `round(float $val [, int $precision = 0])` | This is how older versions of the manual marked optional arguments. The square brackets are not part of the call | + +For example, the notation `int|float $num` describes a single parameter. The call `round(-5.5)` passes it the number `-5.5` and returns the number `-6`. Neither the type, nor the name `$num`, nor the `|` sign go into the call. + +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. + +## Working with an unfamiliar function + +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. + +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..deaee815 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,63 @@ 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. La página de una función en el [manual de PHP](https://www.php.net/manual/es/) se divide en secciones. La sección «Descripción» contiene la firma, es decir, el nombre de la función, sus parámetros y su orden. La sección «Parámetros» explica para qué sirve cada parámetro, y la sección «Valores devueltos» describe el resultado. Para escribir una llamada hacen falta las tres secciones. -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í: +Veamos la [referencia de `round()`](https://www.php.net/manual/es/function.round.php). Si la simplificamos un poco, 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. -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. +La tabla relaciona las partes de la firma con los argumentos de esa llamada. -## Cómo trabajar con funciones nuevas +| 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 | -Cuando te encuentras con una función nueva, puedes usar un patrón sencillo: +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. -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 sección «Valores devueltos» precisa el resultado. La referencia de `round()` dice que la función devuelve un número de punto flotante (`float`) redondeado a la precisión indicada. Por eso, incluso al redondear a entero, el resultado sigue siendo un número fraccionario. -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. +En la firma completa de la documentación hay un parámetro opcional más, `$mode`, que controla el modo de redondeo. Se necesita pocas veces, por lo que de momento no lo analizamos. + +Comprobemos los dos casos en la consola interactiva de PHP, que se inicia con el comando `php -a`. La línea `php >` es el indicador de la consola. La consola no imprime el resultado por sí sola, así que lo mostramos con la función `var_dump()`, que enseña el tipo y el valor. + +```console +php > var_dump(round(10.25, 1)); +float(10.3) +php > var_dump(round(10.25)); +float(10) +``` + +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` 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 | +| `?string $decimal_separator` | El signo `?` permite pasar el valor `null` en lugar de una cadena | +| `round(float $val [, int $precision = 0])` | Así se marcaban los argumentos opcionales en versiones antiguas del manual. Los corchetes no forman parte de la llamada | + +Por ejemplo, la notación `int|float $num` describe un solo parámetro. La llamada `round(-5.5)` le pasa el número `-5.5` y devuelve el número `-6`. Ni el tipo, ni el nombre `$num`, ni el signo `|` se copian en esa llamada. + +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. + +## Trabajar con una función desconocida + +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. + +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..f3522f25 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,63 @@ round(10.25) → аргументы: 10.25, (0) → 10 └── значение по умолчанию ``` -Количество необязательных параметров зависит от конкретной функции, но обязательные всегда идут перед необязательными. +В сигнатуре `round()` обязательный параметр `$num` стоит перед необязательным `$precision`. У другой функции количество параметров и их значения по умолчанию могут отличаться. -## Сигнатура функции +## Как читать документацию функции -У каждой функции есть **сигнатура**, содержащая описание ее имени, параметров и порядка их использования. Сигнатура помогает понять, какие данные функция ожидает и что будет происходить, если параметры не указаны. +Документация описывает, какие данные принимает функция и какой результат возвращает. Страница функции в [руководстве PHP](https://www.php.net/manual/ru/) делится на разделы. Раздел «Описание» содержит сигнатуру, то есть имя функции, параметры и их порядок. Раздел «Список параметров» объясняет назначение каждого параметра, а раздел «Возвращаемые значения» описывает результат. Чтобы составить вызов, нужны все три раздела. -Посмотрим на [документацию](https://www.php.net/manual/ru/function.round.php) для функции `round()`. Если ее немного упростить, сигнатура выглядит так: +Разберём [справку о `round()`](https://www.php.net/manual/ru/function.round.php). Если её немного упростить, сигнатура выглядит так. ```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` означает округление до целого числа. -1. Открыть документацию и найти сигнатуру функции. -2. Посмотреть примеры использования. -3. Перейти в интерактивную оболочку PHP (она запускается командой `php -a`) и попробовать вызвать функцию с разными аргументами. +Раздел «Возвращаемые значения» уточняет результат. В справке о `round()` сказано, что функция возвращает число с плавающей точкой (`float`), округлённое до указанной точности. Поэтому даже при округлении до целого результат остаётся дробным числом. -Такой подход помогает быстро разобраться, как именно работает функция, какие у нее обязательные и необязательные параметры и какие результаты она возвращает. +В полной сигнатуре из документации есть ещё один необязательный параметр `$mode`, который управляет режимом округления. Он нужен редко, поэтому мы его пока не рассматриваем. + +Проверим оба случая в интерактивной оболочке PHP. Она запускается командой `php -a`. Строка `php >` обозначает приглашение оболочки. Оболочка сама результат не печатает, поэтому выведем его функцией `var_dump()`, которая показывает тип и значение. + +```console +php > var_dump(round(10.25, 1)); +float(10.3) +php > var_dump(round(10.25)); +float(10) +``` + +Здесь первый вызов передаёт точность `1` и получает число `10.3`. Второй оставляет `$precision` по умолчанию и получает `10` с типом `float`, как и обещает раздел «Возвращаемые значения». Так мы сопоставляем сигнатуру, объяснение в документации и результат выполнения. + +## Обозначения в справке + +В сигнатуре встречаются служебные обозначения. Они помогают прочитать сигнатуру и при вызове в функцию не передаются. + +| Запись в справке | Как её читать | +| --- | --- | +| `int $precision = 0` | У `$precision` есть значение по умолчанию, аргумент можно пропустить | +| `int\|float $num` | Параметр принимает значение любого из перечисленных типов | +| `?string $decimal_separator` | Знак `?` разрешает передать вместо строки значение `null` | +| `round(float $val [, int $precision = 0])` | Так необязательные аргументы обозначали в старых версиях руководства. Квадратные скобки не входят в вызов | + +Например, запись `int|float $num` описывает один параметр. Вызов `round(-5.5)` передаёт ему число `-5.5` и возвращает число `-6`. Ни тип, ни имя `$num`, ни знак `|` в такой вызов не копируются. + +Если браузер переводит страницу, имена функций, параметров и символы в сигнатуре нужно сверять с оригиналом. На русской версии руководства описания переведены, а сигнатура остаётся на английском. В коде используются исходные имена из документации. + +## Работа с незнакомой функцией + +Чтение справки начинается с задачи. Например, для округления цены до одного знака после запятой в сигнатуре `round()` находим число и точность, в списке параметров проверяем смысл точности, затем пробуем вызов `round(10.25, 1)`. Если результат соответствует описанию, этот вызов можно использовать в программе. + +У другой функции будут свои параметры и правила. По её сигнатуре мы определяем, какие аргументы передать, по описанию узнаём результат и ограничения, а на небольшом примере проверяем своё понимание. From 7a3b007a5c4a0f41c1760628e46c107891093dff Mon Sep 17 00:00:00 2001 From: Nikolay Gagarinov Date: Thu, 5 Nov 2026 16:02:43 +0500 Subject: [PATCH 2/3] =?UTF-8?q?fix(functions):=20=D0=BF=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B5=D1=80=D1=8F=D1=82=D1=8C=20=D0=B2=D1=8B=D0=B7=D0=BE=D0=B2?= =?UTF-8?q?=D1=8B=20=D0=B2=20=D0=BA=D0=BE=D0=BD=D1=81=D0=BE=D0=BB=D0=B8=20?= =?UTF-8?q?PsySH?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: CONTENT-763 Co-Authored-By: Claude Opus 5.5 --- .../en/README.md | 17 ++++++++--------- .../es/README.md | 17 ++++++++--------- .../ru/README.md | 17 ++++++++--------- 3 files changed, 24 insertions(+), 27 deletions(-) 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 8451b684..7b5ef913 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 @@ -65,16 +65,16 @@ The Return Values section specifies the result. The `round()` reference says the The full signature in the documentation has one more optional parameter, `$mode`, which controls the rounding mode. It is rarely needed, so we won't consider it for now. -Let's check both cases in the interactive PHP shell, which starts with the `php -a` command. The `php >` line is the shell prompt. The shell doesn't print results by itself, so we print them with the `var_dump()` function, which shows the type and the value. +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 -php > var_dump(round(10.25, 1)); -float(10.3) -php > var_dump(round(10.25)); -float(10) +> 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` of type `float`, as the Return Values section promises. This is how we match the signature, the explanation in the documentation, and the actual result. +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 @@ -84,10 +84,9 @@ A signature contains auxiliary marks. They help you read the signature and are n | --- | --- | | `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 | -| `?string $decimal_separator` | The `?` sign allows passing `null` instead of a string | -| `round(float $val [, int $precision = 0])` | This is how older versions of the manual marked optional arguments. The square brackets are not part of the call | +| `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 | -For example, the notation `int|float $num` describes a single parameter. The call `round(-5.5)` passes it the number `-5.5` and returns the number `-6`. Neither the type, nor the name `$num`, nor the `|` sign go into the call. +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. 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. 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 deaee815..a2b6d6d0 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 @@ -65,16 +65,16 @@ La sección «Valores devueltos» precisa el resultado. La referencia de `round( En la firma completa de la documentación hay un parámetro opcional más, `$mode`, que controla el modo de redondeo. Se necesita pocas veces, por lo que de momento no lo analizamos. -Comprobemos los dos casos en la consola interactiva de PHP, que se inicia con el comando `php -a`. La línea `php >` es el indicador de la consola. La consola no imprime el resultado por sí sola, así que lo mostramos con la función `var_dump()`, que enseña el tipo y el valor. +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 -php > var_dump(round(10.25, 1)); -float(10.3) -php > var_dump(round(10.25)); -float(10) +> 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` 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. +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 @@ -84,10 +84,9 @@ En la firma aparecen marcas auxiliares. Ayudan a leer la firma y no se pasan a l | --- | --- | | `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 | -| `?string $decimal_separator` | El signo `?` permite pasar el valor `null` en lugar de una cadena | -| `round(float $val [, int $precision = 0])` | Así se marcaban los argumentos opcionales en versiones antiguas del manual. Los corchetes no forman parte de la llamada | +| `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 | -Por ejemplo, la notación `int|float $num` describe un solo parámetro. La llamada `round(-5.5)` le pasa el número `-5.5` y devuelve el número `-6`. Ni el tipo, ni el nombre `$num`, ni el signo `|` se copian en esa llamada. +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. 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. 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 f3522f25..58b451b9 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 @@ -67,16 +67,16 @@ round(int|float $num, int $precision = 0): float В полной сигнатуре из документации есть ещё один необязательный параметр `$mode`, который управляет режимом округления. Он нужен редко, поэтому мы его пока не рассматриваем. -Проверим оба случая в интерактивной оболочке PHP. Она запускается командой `php -a`. Строка `php >` обозначает приглашение оболочки. Оболочка сама результат не печатает, поэтому выведем его функцией `var_dump()`, которая показывает тип и значение. +Проверим оба случая в [интерактивной консоли PHP](https://psysh.org/). Строку `` обозначает строку ввода, а под вызовом после знака `=` консоль печатает результат. ```console -php > var_dump(round(10.25, 1)); -float(10.3) -php > var_dump(round(10.25)); -float(10) +> round(10.25, 1) += 10.3 +> round(10.25) += 10.0 ``` -Здесь первый вызов передаёт точность `1` и получает число `10.3`. Второй оставляет `$precision` по умолчанию и получает `10` с типом `float`, как и обещает раздел «Возвращаемые значения». Так мы сопоставляем сигнатуру, объяснение в документации и результат выполнения. +Здесь первый вызов передаёт точность `1` и получает число `10.3`. Второй оставляет `$precision` по умолчанию и получает `10.0`. Консоль показывает дробную часть, потому что результат имеет тип `float`, как и обещает раздел «Возвращаемые значения». Так мы сопоставляем сигнатуру, объяснение в документации и результат выполнения. ## Обозначения в справке @@ -86,10 +86,9 @@ float(10) | --- | --- | | `int $precision = 0` | У `$precision` есть значение по умолчанию, аргумент можно пропустить | | `int\|float $num` | Параметр принимает значение любого из перечисленных типов | -| `?string $decimal_separator` | Знак `?` разрешает передать вместо строки значение `null` | -| `round(float $val [, int $precision = 0])` | Так необязательные аргументы обозначали в старых версиях руководства. Квадратные скобки не входят в вызов | +| `round(float $val [, int $precision = 0])` | Так необязательные аргументы обозначают в сторонних справочниках и статьях. Квадратные скобки не входят в вызов | -Например, запись `int|float $num` описывает один параметр. Вызов `round(-5.5)` передаёт ему число `-5.5` и возвращает число `-6`. Ни тип, ни имя `$num`, ни знак `|` в такой вызов не копируются. +Например, запись `int|float $num` описывает один параметр. Вызов `round(7)` передаёт ему целое число `7` и возвращает `7.0`. Ни тип, ни имя `$num`, ни знак `|` в такой вызов не копируются. Если браузер переводит страницу, имена функций, параметров и символы в сигнатуре нужно сверять с оригиналом. На русской версии руководства описания переведены, а сигнатура остаётся на английском. В коде используются исходные имена из документации. From 126ed1e150877b1316bb330f624be30f5179185e Mon Sep 17 00:00:00 2001 From: Nikolay Gagarinov Date: Thu, 5 Nov 2026 21:21:08 +0500 Subject: [PATCH 3/3] =?UTF-8?q?docs(functions):=20=D0=BF=D0=BE=D0=BA=D0=B0?= =?UTF-8?q?=D0=B7=D0=B0=D1=82=D1=8C=20=D1=84=D1=80=D0=B0=D0=B3=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=20=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20rou?= =?UTF-8?q?nd()=20=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D1=81=D0=BA=D0=B0=D0=B7=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: CONTENT-763 Co-Authored-By: Claude Opus 5.5 --- .../en/README.md | 39 ++++++++++++++--- .../es/README.md | 39 ++++++++++++++--- .../ru/README.md | 42 ++++++++++++++++--- 3 files changed, 102 insertions(+), 18 deletions(-) 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 7b5ef913..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 @@ -40,9 +40,40 @@ In the signature of `round()`, the required parameter `$num` comes before the op ## How to read a function's documentation -Documentation describes what data a function accepts and what result it returns. A function's page in the [PHP manual](https://www.php.net/manual/en/) is split into sections. The Description section contains the signature, that is, the function's name, its parameters, and their order. The Parameters section explains what each parameter is for, and the Return Values section describes the result. You need all three sections to write a call. +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 [reference for `round()`](https://www.php.net/manual/en/function.round.php). 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 @@ -61,10 +92,6 @@ The table matches the parts of the signature to the arguments of this call. 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. -The Return Values section specifies the result. The `round()` reference says the function returns a floating-point number (`float`) rounded to the given precision. That's why the result stays a fractional number even when you round to an integer. - -The full signature in the documentation has one more optional parameter, `$mode`, which controls the rounding mode. It is rarely needed, so we won't consider it for now. - 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 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 a2b6d6d0..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 @@ -40,9 +40,40 @@ En la firma de `round()` el parámetro obligatorio `$num` va antes del opcional ## Cómo leer la documentación de una función -La documentación describe qué datos recibe una función y qué resultado devuelve. La página de una función en el [manual de PHP](https://www.php.net/manual/es/) se divide en secciones. La sección «Descripción» contiene la firma, es decir, el nombre de la función, sus parámetros y su orden. La sección «Parámetros» explica para qué sirve cada parámetro, y la sección «Valores devueltos» describe el resultado. Para escribir una llamada hacen falta las tres secciones. +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 [referencia de `round()`](https://www.php.net/manual/es/function.round.php). 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 @@ -61,10 +92,6 @@ La tabla relaciona las partes de la firma con los argumentos de esa llamada. 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. -La sección «Valores devueltos» precisa el resultado. La referencia de `round()` dice que la función devuelve un número de punto flotante (`float`) redondeado a la precisión indicada. Por eso, incluso al redondear a entero, el resultado sigue siendo un número fraccionario. - -En la firma completa de la documentación hay un parámetro opcional más, `$mode`, que controla el modo de redondeo. Se necesita pocas veces, por lo que de momento no lo analizamos. - 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 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 58b451b9..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 @@ -42,9 +42,43 @@ round(10.25) → аргументы: 10.25, (0) → 10 ## Как читать документацию функции -Документация описывает, какие данные принимает функция и какой результат возвращает. Страница функции в [руководстве PHP](https://www.php.net/manual/ru/) делится на разделы. Раздел «Описание» содержит сигнатуру, то есть имя функции, параметры и их порядок. Раздел «Список параметров» объясняет назначение каждого параметра, а раздел «Возвращаемые значения» описывает результат. Чтобы составить вызов, нужны все три раздела. +Документация описывает, какие данные принимает функция и какой результат возвращает. У каждой функции в [руководстве PHP](https://www.php.net/manual/ru/) своя страница. Ниже приведён фрагмент [справки о `round()`](https://www.php.net/manual/ru/function.round.php), часть текста пропущена. -Разберём [справку о `round()`](https://www.php.net/manual/ru/function.round.php). Если её немного упростить, сигнатура выглядит так. +```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 @@ -63,10 +97,6 @@ round(int|float $num, int $precision = 0): float Знак `=` в `$precision = 0` сообщает о значении по умолчанию. Из этой записи видно, что второй аргумент можно пропустить. Как именно функция использует `0`, объясняет раздел «Список параметров». У `round()` точность `0` означает округление до целого числа. -Раздел «Возвращаемые значения» уточняет результат. В справке о `round()` сказано, что функция возвращает число с плавающей точкой (`float`), округлённое до указанной точности. Поэтому даже при округлении до целого результат остаётся дробным числом. - -В полной сигнатуре из документации есть ещё один необязательный параметр `$mode`, который управляет режимом округления. Он нужен редко, поэтому мы его пока не рассматриваем. - Проверим оба случая в [интерактивной консоли PHP](https://psysh.org/). Строку `` обозначает строку ввода, а под вызовом после знака `=` консоль печатает результат. ```console