2013-02-18 59 views
0

所以我正在閱讀的擴展例外的PHP手冊並閱讀示例代碼。我對以下代碼的問題是:爲什麼var_dump($o)評估爲null?是否因爲類TestException的構造函數拋出異常,因此不允許完成該對象?我幾乎可以肯定這就是原因。PHP手動例外

不過這裏是檢查代碼:

<?php 
/** 
* Define a custom exception class 
*/ 
class MyException extends Exception 
{ 
    // Redefine the exception so message isn't optional 
     public function __construct($message, $code = 0, Exception $previous = null) { 
    // some code 

    // make sure everything is assigned properly 
    parent::__construct($message, $code, $previous); 
} 

// custom string representation of object 
public function __toString() { 
    return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; 
} 

public function customFunction() { 
    echo "A custom function for this type of exception\n"; 
    } 
} 


/** 
* Create a class to test the exception 
*/ 
class TestException 
{ 
    public $var; 

    const THROW_NONE = 0; 
    const THROW_CUSTOM = 1; 
    const THROW_DEFAULT = 2; 

    function __construct($avalue = self::THROW_NONE) { 

     switch ($avalue) { 
      case self::THROW_CUSTOM: 
       // throw custom exception 
       throw new MyException('1 is an invalid parameter', 5); 
       break; 

      case self::THROW_DEFAULT: 
       // throw default one. 
       throw new Exception('2 is not allowed as a parameter', 6); 
       break; 

      default: 
       // No exception, object will be created. 
       $this->var = $avalue; 
       break; 
     } 
    } 
} 


// Example 1 
try { 
    $o = new TestException(TestException::THROW_CUSTOM); 
} catch (MyException $e) {  // Will be caught 
    echo "Caught my exception\n", $e; 
    $e->customFunction(); 
} catch (Exception $e) {  // Skipped 
    echo "Caught Default Exception\n", $e; 
} 

// Continue execution 
var_dump($o); // Null 
?> 

回答

0

Have a look at PHP exception from PHP official site.

例子:

<?php 

class MyException extends Exception { } 

class Test { 
    public function testing() { 
     try { 
      try { 
       throw new MyException('foo!'); 
      } catch (MyException $e) { 
       /* rethrow it */ 
       throw $e; 
      } 
     } catch (Exception $e) { 
      var_dump($e->getMessage()); 
     } 
    } 
} 

$foo = new Test; 
$foo->testing(); 

?>