Skip to content

Instantly share code, notes, and snippets.

@nbari
Created September 5, 2013 14:16
Show Gist options
  • Save nbari/6450693 to your computer and use it in GitHub Desktop.
Save nbari/6450693 to your computer and use it in GitHub Desktop.
PHP chainable method don't get caught when using try/cath
<?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();
@nbari
Copy link
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