Page 1 of 1

Multiple Inheritance Question

Posted: Wed Sep 08, 2010 4:51 am
by cyrix
Hello fellow programmers. I'm trying to really get into OOP and learning the best practices to manage and structure my code correctly.
I have an app that has several classes for back end operations like form generation and database queries.
I would like to be able to create a new class, have it extend a base class that has access to all my backend classes.

So I could achieve something like this:

Code: Select all

class App {
 public $database = new Database(); //new Database class instance
 public $forms = new Forms(); //New Forms class instance
}

class test extends App {
 function test() {
  $this->database->function(parameters);
  $this->forms->function(parameters);
 }
}
database would be my database handling class. And forms would be my form generation class. Any ideas how I can achieve this? Or is there a better way this can be done?

Re: Multiple Inheritance Question

Posted: Wed Sep 08, 2010 5:36 am
by Weirdan
cyrix wrote:Any ideas how I can achieve this?
And what's wrong with what you posted?

Re: Multiple Inheritance Question

Posted: Wed Sep 08, 2010 6:06 am
by cyrix

Code: Select all

<?php
	class Database {
		public function test() {
			return "Database Class";	
		}
	}
	
	class Forms {
		public function test() {
			return "Forms Class";	
		}
	}
	
	class Object {
		public $database;
		public $forms;
		
		function __construct() {
			$this->database = new Database();
			$this->forms = new Forms();
		}
	}
	
	class Users extends Object {
		function __construct() {
			echo $this->forms->test();
		}
	}
	
	$users = new Users();
?>
This code results in the following error:
Fatal error: Call to a member function test() on a non-object in index.php on line 26

Re: Multiple Inheritance Question

Posted: Wed Sep 08, 2010 7:25 am
by Weirdan
You need to call parent::__construct() in your child class constructor. It's not called automatically.

Re: Multiple Inheritance Question

Posted: Wed Sep 08, 2010 1:38 pm
by Jonah Bron

Code: Select all

parent::__construct();

Re: Multiple Inheritance Question

Posted: Wed Sep 08, 2010 3:17 pm
by cyrix
Yup, that was the problem. Didn't know that a child class would not fire its parent's constructor automatically if it has its own constructor. With good reason though, helps to prevent infinite looping. Thanks for your help guys