Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -36,28 +36,89 @@
└── 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.

Check notice on line 76 in modules/35-calling-functions/135-calling-functions-default-params/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-calling-functions/135-calling-functions-default-params/en/README.md#L76

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `PHP` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/35-calling-functions/135-calling-functions-default-params/en/README.md:76:144: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `PHP`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING

```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 `<?php` line in the console, you type the call right away. 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 |

Check notice on line 113 in modules/35-calling-functions/135-calling-functions-default-params/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-calling-functions/135-calling-functions-default-params/en/README.md#L113

Consider simply using “of” instead. (OF_ANY_OF[1]) Suggestions: `of` URL: https://languagetool.org/insights/post/wordiness/ Rule: https://community.languagetool.org/rule/show/OF_ANY_OF?lang=en-US&subId=1 Category: REDUNDANCY
Raw output
modules/35-calling-functions/135-calling-functions-default-params/en/README.md:113:38: Consider simply using “of” instead. (OF_ANY_OF[1])
 Suggestions: `of`
 URL: https://languagetool.org/insights/post/wordiness/ 
 Rule: https://community.languagetool.org/rule/show/OF_ANY_OF?lang=en-US&subId=1
 Category: REDUNDANCY
| `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.

Check notice on line 116 in modules/35-calling-functions/135-calling-functions-default-params/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-calling-functions/135-calling-functions-default-params/en/README.md#L116

There appears to be an unneeded comma here. “Neither…nor” is a correlative conjunction, so a comma should not separate the pair. (NEITHER_NOR_SUPERFLUOUS_COMMA[1]) Suggestions: `` URL: https://languagetool.org/insights/post/word-choice-either-or-neither/ Rule: https://community.languagetool.org/rule/show/NEITHER_NOR_SUPERFLUOUS_COMMA?lang=en-US&subId=1 Category: PUNCTUATION
Raw output
modules/35-calling-functions/135-calling-functions-default-params/en/README.md:116:140: There appears to be an unneeded comma here. “Neither…nor” is a correlative conjunction, so a comma should not separate the pair. (NEITHER_NOR_SUPERFLUOUS_COMMA[1])
 Suggestions: ``
 URL: https://languagetool.org/insights/post/word-choice-either-or-neither/ 
 Rule: https://community.languagetool.org/rule/show/NEITHER_NOR_SUPERFLUOUS_COMMA?lang=en-US&subId=1
 Category: PUNCTUATION

## 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.
Original file line number Diff line number Diff line change
Expand Up @@ -36,28 +36,89 @@
└── 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.

Check notice on line 74 in modules/35-calling-functions/135-calling-functions-default-params/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-calling-functions/135-calling-functions-default-params/es/README.md#L74

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/35-calling-functions/135-calling-functions-default-params/es/README.md:74:68: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC

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í.

Check notice on line 76 in modules/35-calling-functions/135-calling-functions-default-params/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-calling-functions/135-calling-functions-default-params/es/README.md#L76

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `PHP` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/35-calling-functions/135-calling-functions-default-params/es/README.md:76:86: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `PHP`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING

```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.

Check notice on line 93 in modules/35-calling-functions/135-calling-functions-default-params/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-calling-functions/135-calling-functions-default-params/es/README.md#L93

If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE) Suggestions: `El Segundo` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US Category: CASING
Raw output
modules/35-calling-functions/135-calling-functions-default-params/es/README.md:93:4: If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE)
 Suggestions: `El Segundo`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US
 Category: CASING

Check notice on line 93 in modules/35-calling-functions/135-calling-functions-default-params/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-calling-functions/135-calling-functions-default-params/es/README.md#L93

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/35-calling-functions/135-calling-functions-default-params/es/README.md:93:157: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC

Comprobemos los dos casos en la [consola interactiva de PHP](https://psysh.org/). En la consola no se escribe la línea `<?php`, la llamada se teclea directamente. El signo `>` 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

Check notice on line 120 in modules/35-calling-functions/135-calling-functions-default-params/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-calling-functions/135-calling-functions-default-params/es/README.md#L120

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/35-calling-functions/135-calling-functions-default-params/es/README.md:120:5: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC

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.
Loading
Loading