Jump to content

[SOLVED] Need Help Accessing Nested Objects


PirateNinjaNala

Recommended Posts

I am running into problems accessing objects that I have nested within other objects. I am using PHP 5. My workstation is Windows XP, but I'm not sure about the details of the webserver where I work. It might be linux, it might be some version of windows, or some combination. I'm pretty sure the webserver runs Apache. (If the answers to those questions are critical, I will ask my boss whenever he comes back from sick leave.)

Anyway, this is my problem. I first tried using subclasses but discovered that PHP does not allow this, so I included the files for the subclasses into the main class. That little workaround has allowed me to put objects within other objects, but now I can't get them back out! How do I access nested objects?

I have tried searching Google and this site's archive, but I'm having trouble finding anything. I am currently trying something like this. I cannot get this approach to work. What am I doing wrong?

file1.php
<?php
include_once( "file2.php" );
class SuperClass
{
    $this->nestedObjects = array();

    function addObject( $object )
    {
          array_push( $this->nestedObjects, $object );
    }
    function getObjectNumber( $n )
    {
          return $this->nestedObjects[ $n ];
    }
}
?>

file2.php
<?php
class SubClass
{
    function __construct( $name )
    {
          $this->name = $name;
    }
    function getName()
    {
          return $this->name;
    }
}
?>

file3.php
<?php
include_once( "file1.php");
$a = new SuperClass();
$b = new SubClass( "example" );
$a->addObject( $b );
$c = $a->getObjectNumber( 0 );
$c->getName();
?>

Basically, my problem is that the last line of code in file3, $c->getName(), does not work. I keep getting an error message like this one:

[b]Fatal error: Call to a member function getName() on a non-object in file3.php on line 7[/b]

I absolutely cannot figure out how to access the nested object! Please help. Is my approach wrong? Does PHP just not support this? Is there a workaround?

Thank you all for your time.
Link to comment
Share on other sites

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.