Page 1 of 1

Using class called within a function of an extended class pr

Posted: Thu Apr 08, 2010 7:07 pm
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();
	}
}

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

Posted: Thu Apr 08, 2010 10:19 pm
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();
        }
}