TypeError

(PHP 7, PHP 8)

Introdução

Um TypeError pode ser lançado quando:

  • Um valor sendo informado em uma propriedade de classe que não corresponde com o tipo declarado.
  • O tipo do argumento que é passado para uma função que não coincide com o tipo declarado para parâmetro.
  • Um valor sendo retornado de uma função que não coincide com o tipo declarado da função.

Sinopse da classe

class TypeError extends Error {
/* Propriedades herdadas */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Métodos herdados */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

Changelog

Versão Descrição
7.1.0 Um erro TypeError não é lançado quando um número inválido de argumentos é passaod para uma função nativa, no modo estrito. Lança agora um erro ArgumentCountError.
add a note

User Contributed Notes 3 notes

up
4
celsowmbr at outlook dot com
4 years ago
An example:

<?php

function test($x):int {
    return
$x;
}

try {
   
test('ss');
}catch(
TypeError $e){
    echo
"Error !";
}
up
0
nibeyrovictor at outlook dot com dot ar
2 hours ago
<?php
declare(strict_types=1);

function
sumarEnteros(int $entero1, int $entero2): int | float {
    return (
$entero1 + $entero2)/3 ;
}

$resultado = sumarEnteros(2, 6);
echo
$resultado;
?>
<!DOCTYPE html>
<html>
<head>
    <title>Suma en PHP</title>
</head>
<body>
</body>
</html>
up
-12
andrian dot test dot job at gmail dot com
3 years ago
declare(strict_types=1); //if without this line the result is different

$a = [1,2=>[3,4]];

try{

    count($a, COUNT_RECURSIVE, 'toto and blabla');

}catch(TypeError $e){

    echo $e->getMessage();

}
To Top