I am wondering if there is any way to implement some sort of "reverse visibility" in PHP? I understand that children can access public and protected members of a parent class, like this:

class A {

protected function __construct() { echo 'yes'; }

}

class B extends A {

public function __construct() { parent::__construct(); }

}

$b = new B; // yes
$a = new A; // fatal error

What I am hoping for is the opposite. I would like some way of making A able to call B's constructor, but B unable to call A's, without A being a subclass of B. Ideally, neither of them would be subclasses -- they would be two distinct classes.

I know that some languages have something called "nested classes" which can accomplish this. Is there any way to trick PHP into doing it, since it doesn't support nested classes?

I have read through this SO question: https://stackoverflow.com/questions/16424257/nested-or-inner-class-in-php but it all sounds a bit to "hack-y" to me. It's also three years old. Perhaps PHP 7 has made some improvements that might make this easier?

    I don't see how an instance of a class could call a subclass's constructor - which of the indeterminate number of subclasses would it call?

    Class A could be abstract and declare an abstract "initialise()" method that then gets implemented by subclasses. A's own constructor would include a call to $this->initialise().

    The top answer to that SO question notes a few conventional approaches that don't involve namespacing and dancing around with reflection (the latter of which I don't like either).

    There is a mechanism for importing (common) methods into classes independently of the class hierarchy, if that helps; see [man]traits[/man].

      Well, I guess I'm not looking to call the constructor in the same sense as you would with a parent's (as above). What I'm looking for is to instantiate B from within A, but not outside of it. A problem that is very easily solved with nested classes:

      public class A {
      
      private $MyB;
      
      private class B {
      	// ...
      }
      
      public function __construct() {
      	$this->MyB = new B;
      }
      
      }
        Write a Reply...