Jump to content

Working Through a Book - Undefined Variable


BorysSokolov
Go to solution Solved by Jessica,

Recommended Posts

I'm working through an example in the book Pro PHP and jQuery by Jason Lengstorf, and keep receiving the error

Notice: Undefined variable: db in ...\sys\class\class.db_connect.inc.php on line 30

I do know why I am receiving the error, but I am not sure how to go about solving it. I'm not exactly sure what the author meant to do with the variable db.

 

Here's the code:

class DB_Connect {
	/**
	 * Stores a database object
	 *
	 * @var object A database object
	 */
	protected $db;
	 
	/**
	 * Checks for a DB object or creates one if one isn't found
	 *
	 * @param object $dbo A database object
	 */
	protected function __construct($dbo=NULL)//assigns $dbo a default value
	{
		if(is_object($db)){
			$this->db = $db;
		}else{
			//Constants are defined in /sys/config/db-cred.inc.php
			$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME;
			try{
				$this->db = new PDO($dsn, DB_USER, DB_PASS);
			}catch(Exception $e){
				//If the DB connection fails, output the error
				die($e->getMessage());
			}
		}
	}
}

Nowhere in the code is the variable ever assigned a value, or even declared, prior to making the check, so I'm not even sure what's it supposed to do. I double-checked that I haven't missed any code, but surely I must have omitted something...

 

Can anyone figure it out?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.