[英]Exception handling in oop PHP not working
我是面向對象的PHP的新手,並嘗試一些基本示例來了解oop php。 我上面有一個簡單的例子,其中我試圖學習異常處理並在年齡大於20但無法正常工作時生成異常錯誤消息。
<?php
interface read_methods
{
public function read_age($age);
}
abstract class person
{
var $gender;
var $animal;
var $birds;
abstract function group($group);
function people($value)
{
$this->gender=$value;
}
function animals($value)
{
$this->animal=$value;
}
function bird($value)
{
$this->birds=$value;
}
}
class behaviour extends person implements read_methods
{
var $nonhuman;
function get_all()
{
return $this->people();
return $this->animals();
return $this->bird();
}
function non_human($nonhuman)
{
return $this->alien=$nonhuman;
}
function read_age($age)
{
try {
$this->age=$age;
}
catch(Exception $e)
{
if ($age > 20)
{
throw new Exeption("age exceeds",$age, $e->getMessage());
}
}
}
function group($group)
{
return $this->group=$group;
}
}
$doerte=new behaviour();
$doerte ->people(array('male','female'));
$doerte ->animals(array('fish','whale'));
$doerte ->bird(array('parrot','crow'));
$doerte->non_human('alien');
$doerte->read_age('23');
$doerte->group('living_things');
//$doerte->__autoload();
print_r($doerte);
?>
您將異常放在錯誤的位置。
如果無效,則需要拋出。 那屬於嘗試部分。 catch部分用於處理異常。
這樣想:如果程序必須大喊大叫以尋求幫助,則拋出異常,因為它不知道如何處理數據(嘗試)。 應該使用異常塊來解決該哭泣以尋求幫助
function read_age($age)
{
try {
if($age > 20) {
throw new Exception('Too old!');
}
$this->age=$age;
}
catch(Exception $e)
{
echo 'There has been an error: '.$e->getMessage();
}
}
您檢查過PHP錯誤日志了嗎? 可能是拼寫錯誤的“ Exeption”,應為“ Exception” => new \\ Exception(...
@Debflav:對不起,我的雙重職位。 您的答案當時沒有顯示在我的屏幕上
您想在年齡超過20歲時創建例外嗎? 這可能是一個解決方案(部分代碼):
/* ... */
function read_age($age)
{
if ($age > 20) {
throw new Exception("age exceeds, shoulw be less than 20");
} else {
$this->age=$age;
}
}
/* ... */
try {
$doerte=new behaviour();
$doerte ->people(array('male','female'));
$doerte ->animals(array('fish','whale'));
$doerte ->bird(array('parrot','crow'));
$doerte->non_human('alien');
$doerte->read_age('23');
$doerte->group('living_things');
echo "It's all right";
print_r($doerte);
} catch (Exception $e) {
echo "Something went wrong: ".$e->getMessage();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.