Base de connaissancesCentre d’examen
FRFrançais
Choisir la langue13

CKTIS / PHP

BadMethodCallException

BadMethodCallException spécialise BadFunctionCallException pour un appel de méthode invalide.

Version : PHP 8.4; repository runtime, production runtime not attested

Syntaxe

throw new BadMethodCallException("unknown method")

BadMethodCallException spécialise BadFunctionCallException pour un appel de méthode invalide. Un gestionnaire __call peut la lever explicitement pour un nom inconnu. Une méthode absente sans gestionnaire magique provoque une Error du moteur qui échappe à la capture de cette exception SPL.

class Palette {
    public function __call(string $name, array $args): mixed {
        if ($name === "red") { return "#f00"; }
        throw new BadMethodCallException($name);
    }
}
$p = new Palette(); echo $p->red(), PHP_EOL;
try { $p->blue(); } catch (BadMethodCallException $e) { echo get_class($e), " ", $e->getMessage(), PHP_EOL; }
try { (new stdClass())->blue(); } catch (Error $e) { echo get_class($e); }
#f00
BadMethodCallException blue
Error

Exemples

<?php
class Palette {
    public function __call(string $name, array $args): mixed {
        if ($name === "red") { return "#f00"; }
        throw new BadMethodCallException($name);
    }
}
$p = new Palette(); echo $p->red(), PHP_EOL;
try { $p->blue(); } catch (BadMethodCallException $e) { echo get_class($e), " ", $e->getMessage(), PHP_EOL; }
try { (new stdClass())->blue(); } catch (Error $e) { echo get_class($e); }

Résultat

#f00
BadMethodCallException blue
Error

Sources