2

I do this type of thing in Java all the time, and I'm trying to figure out if it's possible in PHP. This is what I would expect the syntax to look like if it was possible, but I'm wondering if there's some special way to do it (if it's possible, that is).

class Foo { public static class FooBarException extends Exception { } public static class BarBazException extends Exception { } public function DoSomething() { try { // Calls to other class methods that can // throw FooBarException and BarBazException } catch (self::FooBarException $e) { // Stuff.. } } } $bang = new Foo(); try { $bang->DoSomething(); } catch (Foo::BarBazException $e) { // Stuff.. } 
4
  • As an aside, I forgot if there's an actual name for doing this, in any language. I thought it was "subclass", but that would be used as "FooBarException is a subclass of Exception"... Commented Feb 22, 2012 at 21:16
  • Aside for your aside, I think you are looking for 'inner class', and here is a link to a similar question: stackoverflow.com/questions/4351782/… Short answer is 'No' Commented Feb 22, 2012 at 21:19
  • It's also called "nested classes". Commented Feb 22, 2012 at 21:20
  • @watcher and linepogl - thanks, that would be why I couldn't find duplicates. "Member class" kept getting treated as "class members" in searches... Commented Feb 22, 2012 at 21:28

3 Answers 3

3

No, you can not. However, introduced in PHP 5.3 are namespaces. With namespaces you could similarly do:

<?php namespace MyNamespace { use Exception; class FooBarException extends Exception { } class FooBazException extends Exception { } class Foo { public function doSomething() { throw new FooBarException; } } } namespace AnotherNamespace { $bang = new \MyNamespace\Foo; try { $bang->doSomething(); } catch(\MyNamespace\FooBarException $up) { throw $up; // :) } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Disappointing, but +1 and accept because I didn't even know about namespaces.
1

No, it is not possible.

You can use namespaces for a similar effect, however.

Comments

1

You cann't do it in PHP, but in php 5.3 you can use namespaces for similar functionality

http://php.net/namespace

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.