class inside a class..possible?

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
User avatar
pleigh
Forum Contributor
Posts: 445
Joined: Wed Jan 19, 2005 4:26 am

class inside a class..possible?

Post by pleigh »

is this possible?a class inside another class?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

What do you mean specifically?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

class Class_One 
	{
		public function __construct() 
		{
			class Class_Two 
			{ 
				public function __construct() {
				
				}
			}
		}
	}
Why don't you try it yourself?
User avatar
pleigh
Forum Contributor
Posts: 445
Joined: Wed Jan 19, 2005 4:26 am

Post by pleigh »

sorry for not being brief...if i have a Page class and another class for database query, can i include the database class inside the Page class??

sorry for the lame example.. :oops:
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

I don't know if your after the EXTENDS keyword or not..

if you don't want to extend to page class to the database class, you can either pass the database object to the page class.. as in:

Code: Select all

$database = new DatabaseQueryClass();

$pageController = new PageController(&$database);
Although I personally use a singleton pattern to access my database class from wherever I need.
User avatar
pleigh
Forum Contributor
Posts: 445
Joined: Wed Jan 19, 2005 4:26 am

Post by pleigh »

u mean like require_once('/dbconnection.php') in every page?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

What you probably want is composition, like:

Code: Select all

class Page {
        private $db;

	public function __construct($db) {
                $this->db = $db;
	}

	public function render() {
                $result = $this->db->query($sql);
	}
}

$db = new Database($dsn);
$page = new Page($db);
$output = $page->render();
(#10850)
Post Reply