Using class called within a function of an extended class pr

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Roaches
Forum Newbie
Posts: 3
Joined: Fri Feb 22, 2008 7:33 pm

Using class called within a function of an extended class pr

Post by Roaches »

I'm trying to initialize a class within a function that is inside a class and use that class within an extended class, but having a problem with the extended class not being able to find it. Not the exact code I'm using, but same structure:

Code: Select all

class A {
	function test() {
		$this->class = new class;
	}
}

class B extends A {
	function B() {
		$this->class2 = new C;
	}
}

class C extends B {
	function C() {
		$this->class->function();
	}
}
But I get a "Call to a member function function() on a non-object" error.

It works if I do this, but I would prefer not to have to do it if I don't have do:

Code: Select all

class C extends B {
	function C() {
		global $a;
		
		$a->class->function();
	}
}
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Using class called within a function of an extended clas

Post by requinix »

1. Parent constructors aren't called automatically. You have to do it yourself:
2. Nowhere do you call the "test" method, so $this->class is never set.

Code: Select all

class A {
        function test() {
                $this->class = new class;
        }
}

class B extends A {
        function B() {
                parent::test();
                $this->class2 = new C;
        }
}

class C extends B {
        function C() {
                parent::B();
                $this->class->function();
        }
}
Post Reply