Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ba73b05

Browse files
committed
add stringable interface section
1 parent a68f1c5 commit ba73b05

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

translations/es-AR.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1489,3 +1489,61 @@ showType(true); // "Boolean"
14891489

14901490
- [Match expression on PHP.Watch](https://php.watch/versions/8.0/match-expression)
14911491

1492+
### Interfaz Stringable
1493+
1494+
![php-version-80](https://shields.io/badge/php->=8.0-blue)
1495+
1496+
Desde PHP 8.0, hay una nueva interfaz llamada `Stringable`, que indica que una clase tiene un método mágico `__toString()`. PHP agrega automáticamente la interfaz `Stringable` a todas las clases que implementan ese método.
1497+
1498+
```php
1499+
interface Stringable {
1500+
public function __toString(): string;
1501+
}
1502+
```
1503+
1504+
Cuando se define un parámetro con el tipo `Stringable`, comprobará que la clase dada implementa la interfaz `Stringable`:
1505+
1506+
```php
1507+
class Foo {
1508+
public function __toString(): string {
1509+
return 'bar';
1510+
}
1511+
}
1512+
1513+
function myFunction(Stringable $param): string {
1514+
return (string) $param;
1515+
}
1516+
$a = myFunction(new Foo);
1517+
// $a = 'bar'
1518+
```
1519+
1520+
Si una clase dada no implementa `__toString()`, obtendrá un error:
1521+
1522+
```php
1523+
class Foo {
1524+
}
1525+
1526+
function myFunction(Stringable $param): string {
1527+
return (string) $param;
1528+
}
1529+
$a = myFunction(new Foo);
1530+
// TypeError: myFunction(): Argument #1 ($param) must be of type Stringable, Foo given
1531+
```
1532+
1533+
Un tipo `Stringable` no acepta `string`:
1534+
1535+
```php
1536+
function myFunction(Stringable $param): string {
1537+
return (string) $param;
1538+
}
1539+
$a = myFunction('foo');
1540+
// TypeError: myFunction(): Argument #1 ($param) must be of type Stringable, string given
1541+
```
1542+
1543+
Por supuesto, para aceptar tanto `string` como `Stringable`, puede usar un tipo de unión:
1544+
1545+
```php
1546+
function myFunction(string|Stringable $param): string {
1547+
return (string) $param;
1548+
}
1549+
```

0 commit comments

Comments
 (0)