• 0

[PHP] Parent/Child object relations


Question

Ok so I have a couple classes that Ive written.

The first is a SQL class basically creating an object that will open a new sql connection and run queries.

class sqlConnection {

	public $connection;

	public function __construct($host, $username, $password){
		// Setup new connection and save it in the $connection variable.
	}
}

My next two classes are where it gets kind of tricky- we'll call them class Mommy and Daughter... Daughter is an extension of Mommy. Daughter also has child objects of its self within its self.

class Mommy {

	public $_GLOBAL = array("dbconnection" => array(),
				"somevariable" => "value");

	public function __construct($variable_value){
		$this->_GLOBAL["somevariable"] = $variable_value;
	}
	public function setDBConnection($id, $connection){
		$this->_GLOBAL["dbconnection"][$id] = $connection;
	}
	public function getDBConnection($id){
		return $this->_GLOBAL["dbconnection"][$id];
	}
}

class Daughter extends Mommy {

	public $child = array();

	public function __construct(){
		// This code creates multiple Daughter children within themselves which get mounted onto the $child array.
	}
}

The Daughter class is also where the sqlConnection class gets created and used. However, the sqlConnection object gets mounted on the Mommy $_GLOBAL["dbconnection"] array and is supposed to act as a "Global" database connection for all children within the Daughter class. This is to prevent myself from having to redefine the sqlDatabase class for every child object within the Daughter class.

My problem is that when I define a new Daughter child it carries all of the Mommy variables with it, with the exception of the database connection that I want. If I run a print_r on my root Daughter object it looks kind of like this

Daughter Object (
	[child] => Array (
		[emily] => Daughter Object (
			[child] => Array(...)
			[_GLOBAL] => Array(
				[somevariable] => value
				[dbconnection] => Array()
				)
			)
		)
		[amy] => Daughter Object (
			[child] => Array(...)
			[_GLOBAL] => Array(
				[somevariable] => value
				[dbconnection] => Array()
				)
			)
		)
	)
	[_GLOBAL] => Array(
		[somevariable] => value
		[dbconnection] => Array(
			[] => sqlConnection Object(
				[connection] => Resource id #6
			)
		)
	)
)

As you can see- the "somevariable" variable got passed down to all of the children but the "dbconnection" variable didnt for some reason. Can anyone help me with this?

Link to comment
https://www.neowin.net/forum/topic/666382-php-parentchild-object-relations/
Share on other sites

4 answers to this question

Recommended Posts

  • 0

The mysql_connect() function in PHP returns the currently established database link, if there is one with the same host/user/pass already established, otherwise it creates a new one.

All you need to do is create a database connection using "sqlConnection" in your "Daughter" constructor. You won't end up with multiple database connections, just one. You don't really need the "Mommy" class to achieve this either.

It's a bit weird that your "Daughter" constructor is returning instances of itself within an array. You should probably take a look at the PHP5 OO manual to get a better feel for OO and how you can use it to your advantage.

Edited by ziadoz
  • 0

Well its a template class and the daughter class parses through my code and creates a new instance of its self per every "child" object in the html.

It seems like the mysql connections dont get carried down through the child objects since its being defined somewhere else in the child process.

  • 0

I guess what you're trying to achieve is an inherited $connection variable (I figured you were more concerned about duplicate MySQL connections in my previous post). That's pretty simple to achieve:

<?php
class sqlConnection {

	protected $connection;

	private $host = 'localhost';
	private $user = 'root';
	private $pass = '';
	private $db = 'test';

	public function __construct(){
		$this->connection = mysql_connect($this->host, $this->user, $this->pass);
		mysql_select_db($this->db, $this->connection);
	}
}

class Daughter extends sqlConnection {
	public $child = array();

	public function __construct(){
		parent::__construct();
		// This code creates multiple Daughter children within themselves which get mounted onto the $child array.
	}

	public function test() {
		$query = mysql_query('SELECT COUNT(*) FROM test', $this->connection);
		return mysql_result($query, 0, 0);
	}
}

$d = new Daughter;
echo $d->test();
?>

In the code when Daughter is constructed it will also construct its parent (sqlConnection) and inherit the $connection attribute (holding the MySQL link). I've made $connection protected which means only the parent and any descendants (i.e. Daughter) can access it. Also I've removed the parameters from the sqlConnection constructor and made them private class attributes (meaning only sqlConnection can access them). You could pull the connection attributes (host, user, pass and db) from an external configuration file or something if necessary. The test() function will simply perform a query using the inherited $connection link and return the result.

Hopefully this helps you understand inheritance (and polymorphism) some more. :)

Edited by ziadoz
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I agree. I also think Phil stayed too long. They should definitely fire whoever thought all a console platform needed was Call of Duty, Elder Scrolls, and Fallout to survive. Asha and crew are still saying they need more Elder Scrolls and Fallout games. They simply don't get it.
    • Macbook Air is an appealing option, as are plethora of Windows devices with various different CPU's
    • Mozilla highlights Firefox Nova 2026 redesign and more upcoming features with new roadmap by Sayan Sen Last month Mozilla confirmed that Firefox was set to get a major redesign this year. Dubbed "Project Nova", it can already be tested and will roll out to all users later this year.The idea is to keep the browser competitive in a rapidly evolving internet landscape. As such the revamp focuses on improving privacy, usability, performance, accessibility, and customization. Key privacy features including the built-in VPN, private browsing mode, and Enhanced Tracking Protection, will be more visible and easier to manage, while users will have the option to disable AI features entirely through a dedicated kill switch. Additionally, the redesign promises faster page loading, the return of Compact mode, expanded personalization options, and stronger accessibility support. You can find the full details in the dedicated piece linked above. In a new blog post today the company once again reiterated on Nova and also emphasized other new and upcoming features like the settings revamp that is intended to make it easier for users to understand browser settings. In order to make it simpler for users to keep up with such features Mozilla today is launching Firefox roadmap. Hence enthusiasts and interested users will be able to check out what's cooking and also share feedback about the upcoming additions. Alongside the roadmap announcement, Mozilla also highlighted what's new in Firefox 152. One of the biggest additions is the arrival of Tab Groups on Android. The feature, which has already been helping desktop users organize large numbers of tabs, is now beginning to roll out on mobile. Users will be able to group related tabs together, assign names and colors to them, and return to them later. Mozilla says support for iOS will arrive later this year. Firefox 152 also introduces the aforementioned redesigned Settings experience. The company says the changes are meant to make controls easier to find and help users discover features they may not have previously known about. Existing preferences are not changing, though they are now better organized. Another notable addition is the new Blocked Tracker Widget, which provides a visual overview of Firefox's privacy protections by showing how many trackers have been blocked over time and the types of tracking activity the browser has stopped. Looking ahead, Mozilla revealed several upcoming roadmap features. They include customizable keyboard shortcuts, as well as enhanced PDF editing tools that will allow documents to be split, merged, and reorganized directly within Firefox. The company is also working on bringing Multi-Account Containers into the native Firefox experience thus removing the need for a separate extension. Meanwhile Firefox's built-in VPN is set to expand to mobile devices. Mozilla is also developing AI-powered features like Quick Answers, which can provide concise responses to voice queries, and Smart Window, its optional AI browsing experience that is now available without a waitlist. Finally, a new Power Saving Mode is in the works and will help reduce the impact of resource-heavy tabs on mobile devices in order to extend battery life. The video below summarizes the upcoming changes in an easy to understand format: You can find the announcement blog post here on Mozilla's official website.
    • Dead on arrival at that price. Like they missed the mark by multiple hundreds of dollars - this should actually undercut the Macbook Air at $899 if they want any sort of sales / further adoption of WoA
  • Recent Achievements

    • One Year In
      Console General earned a badge
      One Year In
    • One Year In
      Twozo Technologies earned a badge
      One Year In
    • One Month Later
      Twozo Technologies earned a badge
      One Month Later
    • Week One Done
      Twozo Technologies earned a badge
      Week One Done
    • Veteran
      branfont went up a rank
      Veteran
  • Popular Contributors

    1. 1
      +primortal
      513
    2. 2
      +Edouard
      196
    3. 3
      PsYcHoKiLLa
      109
    4. 4
      Steven P.
      89
    5. 5
      Nick H.
      71
  • Tell a friend

    Love Neowin? Tell a friend!