Statement on glibc/iconv Vulnerability

A interface Stringable

(PHP 8)

Introdução

A interface Stringable denota uma classe que tenha um método __toString(). Diferentemente da maioria das interfaces, Stringable está implicitamente presente em qualquer classe que possua o método mágico __toString() definido, embora ela possa e deveria ser declarada explicitamente.

Seu principal valor é permitir que funções façam verificações de tipo em uniões string|Stringable para aceitar tanto uma string primitiva quanto um objeto que possa ser convertido para uma string.

Resumo da Interface

interface Stringable {
/* Métodos */
public __toString(): string
}

Exemplos de Stringable

Exemplo #1 Uso Básico de Stringable

<?php
class IPv4Address implements Stringable {
private
string $oct1;
private
string $oct2;
private
string $oct3;
private
string $oct4;

public function
__construct(string $oct1, string $oct2, string $oct3, string $oct4) {
$this->oct1 = $oct1;
$this->oct2 = $oct2;
$this->oct3 = $oct3;
$this->oct4 = $oct4;
}

public function
__toString(): string {
return
"$this->oct1.$this->oct2.$this->oct3.$this->oct4";
}
}

function
showStuff(string|Stringable $value) {
// A Stringable will get converted to a string here by calling
// __toString.
print $value;
}

$ip = new IPv4Address('123', '234', '42', '9');

showStuff($ip);
?>

O exemplo acima produzirá algo semelhante a:

123.234.42.9

Índice

add a note

User Contributed Notes 1 note

up
33
Gormack
2 years ago
Since it's introduced in PHP 8, IPv4Address class Example #1 could be shortened to:
<?php
class IPv4Address implements Stringable {
public function
__construct(private string $oct1, private string $oct2, private string $oct3, private string $oct4) {
}

public function
__toString(): string {
return
"$this->oct1.$this->oct2.$this->oct3.$this->oct4";
}
}
?>
To Top