我正在尝试学习更多PHP oop的东西 -
我在这里找到了下面的代码块......
我正在传递" PC"触发"无效平台的构造函数"异常 - 它被我添加的try catch块捕获,但随后调用printCode
会得到一个"未定义的索引"我期望的错误" PC"不在数组platformArray
..
我的问题是处理所有这些异常/错误的正确方法是什么?你应该为每个函数都有一个try catch块吗?
<?php
include('Logger.php');
class Platform
{
private static $platformArray = array (
'ps3' => array ('displayName' => 'playstation 3', 'function' => 'funcPS3'),
'xbox' => array ('displayName' => 'Xbox', 'function' => 'funcXbox')
);
private $type;
public function __construct($log, $type)
{
try {
if (!array_key_exists($type, self::$platformArray)) {
throw new Exception("Invalid Platform type $type");
}
$this->type = $type;
} catch (Exception $e) {
$log->write_error_log("0", "good_bad_code1.php", $e->getMessage());
}
}
public function printCode()
{
// This was a question embedded within your question, you can use
// http://php.net/manual/en/function.call-user-func.php
// and pass an instance with a method name.
return call_user_func(array ($this, self::$platformArray[$this->type]));
}
private function funcPS3()
{
echo 'ps3 specific code';
}
private function funcXbox()
{
echo 'xbox specific code';
}
}