0

what may be the best way to ensure that only one specific class can create an instances of another specific class in PHP without something like nesting classes? Is there any pattern or am I forced to use the Reflection API?

Example: Only object/class A is able to create objects of class B.

lsblsb
  • 1,292
  • 12
  • 19
  • 1
    There has been some talk about an RFC for "private classes", but there is no formal method for doing this in PHP – Mark Baker Feb 24 '15 at 08:13
  • http://stackoverflow.com/a/16424902/4098311 – Halayem Anis Feb 24 '15 at 08:22
  • Namespaces are at least an interesting approach... – lsblsb Feb 24 '15 at 08:33
  • This does not sound like a good idea. For one, it's death of testability. More generally, you're just handcuffing yourself, taking away flexibility which you may come to regret later. If you don't want certain classes to instantiate other classes, just don't instantiate them. Unless you write code which instantiates them, they won't be instantiated. Maybe use a certain naming convention to hint at who may instantiate whom. – deceze Feb 24 '15 at 08:52

1 Answers1

0

You can check the caller using debug_bugtrace()

class Foo
{
  public function __construct()
  {
    $bar = new Bar();
    $bar->test();
  }
}

class Bar
{
  public function test()
  {
      $trace = debug_backtrace();
      if (isset($trace[1])) {
          // $trace[0] is ourself
          // $trace[1] is our caller
          // and so on...
          var_dump($trace[1]);

          echo "called by {$trace[1]['class']} :: {$trace[1]['function']}";

      }
  }
}
$foo = new Foo();

This example prints called by Foo :: __construct

Then you can check the caller's name and deny instatiation when the caller is not the one

Find out which class called a method in another class

Community
  • 1
  • 1
Phate01
  • 2,499
  • 2
  • 30
  • 55