国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Umformulierter Titel: Warum behandelt PHP die Fehler ?Klasse nicht gefunden' nicht?
P粉475126941
P粉475126941 2024-01-03 19:53:41
0
2
642

Im folgenden Beispiel m?chte ich den Fehler abfangen und eine Null-Klasse erstellen, wenn die Klasse nicht existiert.

Aber trotz meiner try/catch-Anweisung sagt mir PHP einfach 未找到 'SmartFormasdfasdf' 類 .

Wie kann man PHP dazu bringen, ?Class Not Found“-Fehler abzufangen?

<?php
class SmartFormLogin extends SmartForm {
    public function render() {
        echo '<p>this is the login form</p>';
    }
}

class SmartFormCodeWrapper extends SmartForm {
    public function render() {
        echo '<p>this is the code wrapper form</p>';
    }
}

class SmartFormNull extends SmartForm {
    public function render() {
        echo '<p>the form "' . htmlentities($this->idCode) . '" does not exist</p>';
    }
}

class SmartForm {

    protected $idCode;

    public function __construct($idCode) {
        $this->idCode = $idCode;
    }

    public static function create($smartFormIdCode) {
        $className = 'SmartForm' . $smartFormIdCode;
        try {
            return new $className($smartFormIdCode);
        } catch (Exception $ex) {
            return new SmartFormNull($smartformIdCode);
        }
    }
}

$formLogin = SmartForm::create('Login');
$formLogin->render();
$formLogin = SmartForm::create('CodeWrapper');
$formLogin->render();
$formLogin = SmartForm::create('asdfasdf');
$formLogin->render();
?>

L?sung:

Danke @Mchl, so habe ich es gel?st:

public static function create($smartFormIdCode) {
  $className = 'SmartForm' . $smartFormIdCode;
  if(class_exists($className)) {
    return new $className($smartFormIdCode);
  } else {
    return new SmartFormNull($smartFormIdCode);
  }
}


P粉475126941
P粉475126941

Antworte allen(2)
P粉680000555

老問(wèn)題,但在 PHP7 中這是一個(gè)可捕獲的異常。盡管我仍然認(rèn)為 class_exists($class) 是一種更明確的方法。但是,您可以使用新的 \Throwable 異常類型執(zhí)行 try/catch 塊:

$className = 'SmartForm' . $smartFormIdCode;
try {
    return new $className($smartFormIdCode);
} catch (\Throwable $ex) {
    return new SmartFormNull($smartformIdCode);
}
P粉810050669

因?yàn)檫@是一個(gè)致命錯(cuò)誤。使用class_exists()函數(shù)檢查類是否存在。

另外:PHP 不是 Java - 除非您重新定義默認(rèn)錯(cuò)誤處理程序,否則它會(huì)引發(fā)錯(cuò)誤而不拋出異常。

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage