Jump to content

Recommended Posts

Is this possible? For example,

 

class outer {
  function out() {
    class inner {
      function in() {
        return 'here!';
      }
    }
    $doit=new inner();
    return $this->doit->two();
  }
}
$test=new outer();
echo $test->out();

 

I get no error when defining the second class but I can't call it.

Link to comment
https://forums.phpfreaks.com/topic/146154-solved-nested-classes/
Share on other sites

I do not think it is possible.

 

You can use class outer extends inner {

 

As far as doing that, yea doubtful. You can however include a class from another file.

 

class outer {
  function out() {
     include('class.inner.php');       

    $doit=new inner();
    return $this->doit->two();
  }
}
$test=new outer();
echo $test->out();

 

Should work. You could also just define that class on the same page and that should work as well.

 

EDIT:

I do not think you had the function "two" defined in the inner class (I think that is what you caught and solved it). Just decided to point it out :)

 

EDITEDIT:

Fatal error: Class declarations may not be nested in C:\wamp\www\test.php on line 4

 

Returned that when trying to nest :)

technically speaking, it's legal (i think), as long as you only try to declare the inner class once. the proper way to do what you want though is like this:

<?php
class outer {
 function out() {
   $this->doit=new inner();
   return $this->doit->in();
 }
}
class inner {
 function in() {
   return 'here!';
 }
}
$test=new outer();
echo $test->out();
?>

 

edit: I take it back, nesting them produces a Fatal Error

Thanks guys, making classes are very new to me and as I've recently started a new job using PHP I'm using them (as mentioned) in an environment already created - just modifying existing code. It's given me many headaches so far as seeing that my website has a "web1.0" look with all tables I'm re-designing the lot with classes and DIVs.

 

I've managed to nest classes by including a PHP file inside a class - works fine.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.