PHP Inheritance help

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
dhui
Forum Newbie
Posts: 14
Joined: Mon May 10, 2010 1:42 pm

PHP Inheritance help

Post by dhui »

I am trying to mess with inheritance in PHP and was wondering why the code below doesn't work.

Test file

Code: Select all

$dbObj = new DbConn;
$dbObj->printDbInfo(); //displays xxxx

$test = new Amfphp();
$test->printDbInfo(); //Doesn't display anything
Parent class

Code: Select all

class DbConn
{ 

	public $hostname;
	public $dbName;
	public $username;
	public $password;

	//Constructor
	public function __construct() 
	{
		$this->hostname = "xxxx";		
		$this->dbName = "xxxx";
		$this->username = "xxx";
		$this->password = "xxx";
	}
	
	public function connect()
	{
		$db_link = mysql_connect($this->hostname, $this->username, $this->password);
		mysql_select_db($this->dbName, $db_link);
	}
	
	public function printDbInfo()
	{
		print($this->hostname);
	}
	
	public function disconnect() 
	{
		mysql_close();
	}
Child Class

Code: Select all

class Amfphp extends DbConn
{
	function __construct()
	{
	}
	
	function getData()
	{
		print("test");
	}
}
I am just trying to call the "printDbInfo" function in my parent class using the child class object created in the test file...but it doesn't print anything. I am assuming it's because it thinks $this->hostname is null...but I dont know how to get it to work.

Any help will be appreciated!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: PHP Inheritance help

Post by AbraCadaver »

If you don't define a __construct() in the child, then the one in the parent will be called. However, once you define a __construct() in the child then you will need to manually call the parent. This allows you to totally override the parent _construct() if you want. So if you don't need it in the child then don't define it. If you do need it, then do this:

Code: Select all

class Amfphp extends  DbConn
{
        function __construct()
        {
		parent::__construct();
        }
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply