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..
}
Problematic
  • 17,567
  • 10
  • 73
  • 85
Izkata
  • 8,961
  • 2
  • 40
  • 50
  • 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"... – Izkata Feb 22 '12 at 21:16
  • Aside for your aside, I think you are looking for 'inner class', and here is a link to a similar question: http://stackoverflow.com/questions/4351782/how-do-i-use-inner-classes-in-php Short answer is 'No' – Jeff Lambert Feb 22 '12 at 21:19
  • It's also called "nested classes". – linepogl Feb 22 '12 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... – Izkata Feb 22 '12 at 21:28

3 Answers3

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; // :)
    }
}
Vitamin
  • 1,526
  • 1
  • 13
  • 27
1

No, it is not possible.

You can use namespaces for a similar effect, however.

linepogl
  • 9,147
  • 4
  • 34
  • 45
1

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

http://php.net/namespace

Electronick
  • 1,122
  • 8
  • 15