title: class within a class in php
body: <p>Here is the problem outline:</p>
  
  <pre><code>    /*First object*/
      class MYCLASS {
  
                /*Some Properties and methods*/
  
                public function foo() {
                       $this-&gt;somevar = 'yes';
                       $this-&gt;display = '&lt;tag&gt;' . $this-&gt;somevar . '&lt;/tag&gt;';
  
                       /*NOTICE this line, not using return, but echo*/
                       echo $this-&gt;display;
                }
      }
  
      /*Second object, instantiating first object inside*/
      class NEXTCLASS {
  
                /*Some Properties and methods*/
  
                public function yoo() {
                       $this-&gt;maa = new MYCLASS;
                       return '123' . $this-&gt;maa-&gt;foo() . '456';
                }
      }
  
      /*Show output*/
      $next = new NEXTCLASS;
      echo $next-&gt;yoo();
  </code></pre>
  
  <p>This should output <code>123&lt;tag&gt;yes&lt;/tag&gt;456</code> but it is showing <code>&lt;tag&gt;yes&lt;/tag&gt;123456</code></p>
  
  <p>I think <code>$this-&gt;maa-&gt;foo()</code>is an <em>object</em> and that's why it is printed before <em>strings</em>. Got 2 relevant links: <a href="https://stackoverflow.com/questions/1468616/call-a-class-inside-another-class-in-php">stack solution</a>, <a href="http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring" rel="nofollow noreferrer"><code>__toString()</code> magic method</a>.</p>
  
  <p><strong>Question is:</strong> Without changing <code>MYCLASS</code> can I alter <code>$this-&gt;maa-&gt;foo()</code> inside <code>NEXTCLASS</code> in any way, that output will be in right order?</p>