我对面向对象的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部分用于处理异常。
可以这样想:如果你的程序因为不知道如何处理数据而不得不大声呼救(try),那么你就抛出了一个异常。异常块应该用来处理呼救声
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();
}
}
要在age超过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();
}
检查过PHP错误日志了吗?可能是拼写错误的"Exception"应该是"Exception" => new 'Exception(…
@Debflav:抱歉发了两个帖子。你的答案还没有显示在我的屏幕上