Created
September 5, 2013 14:16
-
-
Save nbari/6450693 to your computer and use it in GitHub Desktop.
PHP chainable method don't get caught when using try/cath
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace chain; | |
class Chain { | |
public function __construct() { | |
} | |
public function foo() { | |
return $this; | |
} | |
public function bar() { | |
throw new \Exception('catch me'); | |
} | |
} | |
Class Decorator { | |
private $object; | |
public function __construct() { | |
$this->object = new Chain(); | |
} | |
public function __call($method, $args) { | |
try { | |
return call_user_func_array(array($this->object, $method), $args); | |
} Catch (\Exception $e) { | |
echo $e->getMessage(), PHP_EOL; | |
} | |
} | |
} | |
$a = new Decorator(); | |
/** | |
* expected to be caught | |
*/ | |
$a->foo()->bar(); | |
#$a->bar(); |
Author
nbari
commented
Sep 5, 2013
object = new Chain();
} else {
$this->object = $obj;
}
}
public function __call($method, $args) {
try {
$result = call_user_func_array(array($this->object, $method), $args);
if ($result instanceof Chain) {
return new self($result);
} else {
return $result;
}
} Catch (\Exception $e) {
echo $e->getMessage(), PHP_EOL;
}
}
}
$a = new Decorator();
$a->foo()->bar();
# $a->bar();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment