oop PHP中的异常处理无法正常工作

时间:2014-08-26 11:35:08

标签: php oop exception-handling

我是面向对象的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);
?>

3 个答案:

答案 0 :(得分:0)

你把错误扔到错误的地方。

如果某些事情无效,你需要扔掉。这属于尝试部分。 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();
    }               
}

答案 1 :(得分:0)

您检查过PHP错误日志吗?可能是拼写错误的&#34; Exeption&#34;应该是&#34;例外&#34; =&GT;新\ \例外(......

@Debflav:对不起双重帖子。你的回答当时没有显示在我的屏幕上

答案 2 :(得分:0)

您想在年龄超过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();
}
相关问题