oop PHP中的异常处理不起作用 [英] Exception handling in oop PHP not working

查看:103
本文介绍了oop PHP中的异常处理不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于面向对象的PHP,我还是一个新手,他尝试了一些基本示例来帮助oop php。我上面有一个简单的例子,其中我试图学习异常处理并在年龄大于20但无法正常工作时生成异常错误消息。

I am very new to object oriented PHP and trying some basic examples to get good hand on oop php. I have simple exmaple above in which i am trying to learn exception handling and generate an exception error message when age is greater than 20 but not working.

<?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);
?>


推荐答案

您将异常放在错误的位置。

you throw the exception at the wrong place.

如果某些东西无效,则需要抛出。那属于尝试部分。 catch部分用于处理异常。

If something is invalid you need to throw. That belongs to the try part. The catch part is used to handle the exception.

以这种方式思考:如果编程人员不得不大喊大叫以寻求帮助,则抛出异常,因为它不知道如何处理处理数据(尝试)。 $ p

Think of it that way: you trow an exception if you programm has to yell out for help since it doesnt know what to do with data (try). The exception block should be used to take care of that cry for help

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();
    }               
}

这篇关于oop PHP中的异常处理不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆