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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.