You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 {
0 commit comments