title: How implement composition in php
body: <p>I want to implement next fragment of diagram, using PHP. </p>
  
  <p>See <a href="https://i.stack.imgur.com/dixuV.png" rel="noreferrer">composition example</a> diagram below:</p>
  
  <p><a href="https://i.stack.imgur.com/dixuV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dixuV.png" alt="enter image description here"></a></p>
  
  <p>We can implement composition in Java using inner classes.</p>
  
  <p>But there is no analog of "inner class" in PHP.
  Of course, there are traits. But we can use it in more than one class.</p>
  
  <p>I've implemented composition like this:</p>
  
  <pre><code>class Head {
      private static $instance = NULL;
  
      private function __construct(){}
  
      public static function getInstance() {
          $traces = debug_backtrace();
          if (strcmp($traces[1]['class'], 'Human')) {
              echo "&lt;br&gt;Only human has head"; // Exception can be thrown here
              return NULL;
          }
          if (!static::$instance) static::$instance = new self();
          return static::$instance;
      }
  
      public function __toString() {
          return 'Head';
      }
  }
  
  class Human {
      private $head;
  
      public function __construct() {
          $this-&gt;head = Head::getInstance();
      }
  
      public function __toString() {
          return 'I have ' . $this-&gt;head;
      }
  }
  
  class Plant {
      private $head;
  
      public function __construct() {
          $this-&gt;head = Head::getInstance();
      }
  }
  
  $human = new Human();
  echo $human;
  
  $superman = new Plant();
  </code></pre>
  
  <p>Is it right to do so?</p>
  
  <p>Is there better way to implement composition relationship in PHP? </p>