Jump to content

What is the scope of an object created within a class constructor?


darth_tater

Recommended Posts

Long story short, I have a class that does some data verification and session management.  In order to do some of this verification, it needs a database connection.  I am using the MDB2 class;

 

here is a sample of the constructor's code:

 

 

this is a snippet of code from My Class.

 



// FUNCTIONS
function __construct() {

/*

other code here 

*/
	// set up our datbase connection
	global $dsn;					// must use global as to include the one *from* the settings.php include

	$mdb2 =& MDB2::singleton($dsn);

	if (PEAR::isError($mdb2)) {
		die("<H1> THERE WAS AN ERROR </H1>" . $mdb2->getMessage());
	}

	echo("SESSION CLASS: if you see this, then we're goood!");     // some very crude debugging, please ignore this!
}

 

 

Now, i have another function within this same class:

 

public static function data_validateUserName($safeUserName){



	// build the query
	$q = "SELECT uName FROM Users WHERE username = '$safeUserName'";

	$result = $this->$mdb2->query($q);

	if($result->numRows() >= 1){

			// there is 1 or more hits for a username, it is not available!
		return false;

	} else if ($result->numRows() < 1){

			// there is less than 1 row with that username, we're golden!
		return ture;

	}

}

 

 

Inside the constructor, i have correctly set up a MDB2 object.  I was able to run some queries and other things on it *inside* the constructor.  Because of this, i know that it's settings are correct and it is fully working.

 

However, when i try to use that $mdb2 object inside this other method, i get all sorts of errors about that being a bad reference to an object that essentially does not exist.

 

Now, i tried searching here, and didn't get much help, so apologies.  If you've got a link to a similar question, then please post that with a brief explanation of what you searched for to get it...

 

 

Also, the php.net manual is not very helpful about the scope of objects in this particular setup... so please know that i did pour over that before posting here.

 

Thanks for your time, all.

 

 

***** EDIT ******

 

I've thought about doing it another way:

 

Each function is passed in a reference to the MDB2 object as an argument instead of relying on the one that is *suposed to be* built in to the actual class it's self.  Would this be better / more secure / more efficient?!

 

Link to comment
Share on other sites

In the code you posted, $mdb2 in only a local variable within the __construct() function.

 

To make it a class variable, you would need to declare it as a class variable (for example a private variable) -

 

class MyClass
{
    private $mdb2;

.....
}

 

Then you would reference it everywhere within the class using $this->mdb2 -

 

$this->mdb2 =& MDB2::singleton($dsn);

 

 

 

Link to comment
Share on other sites

That's what i though i have declared MDB2 to be a *public* variable **before** the construct function.  I should have included this portion of the code before hand.  My Bad.

 

here is the *actual code*

 

 


class session {

// VARIABLES

public $sesh_id;				// we default to a NULL ID; when we have valid auth credentials, we'll update this

// Other variables not important here....

public $mdb2;					// the pointer to our database object... which we have yet to create an object of!


// FUNCTIONS
function __construct() {

	// the very first thing we need to do is fill up our variables...

	// code used to fill up and initialize the other non important variables here....

	// set up our datbase connection

	global $dsn;					// must use global as to include the one *from* the settings.php include

	$mdb2 =& MDB2::singleton($dsn);
	if (PEAR::isError($mdb2)) {
		die("<H1> THERE WAS AN ERROR </H1>" . $mdb2->getMessage());
	}

	echo("SESSION CLASS if you see this, then we're goood!");
}




}

 

 

I create the variable *before* the constructor, yet can't access it within other methods.

 

any thoughts?

Link to comment
Share on other sites

Using $this->$mdb2 will generally result in a notice, telling you that $mdb2 is undefined (or whatever variable you put). To access class properties you do not need to prefix it with the $ symbol. If you had a variable $mdb2 and it's value was "localhost" (just an example), then it would actually be saying $this->localhost.

 

Example:

class Test {
public $foo = "Hello";

public function __construct(){
	$bar = "foo";
	echo $this->$bar; //will echo Hello
}
}

Link to comment
Share on other sites

Ok, that makes sense.

 

What about object methods, though?

 

I create the variable that is the MDB2 object as PFMaBiSmAd showed me how to above.  And that works, but i still can't access it as he suggested in *other methods*

 

 

 


public static function data_validateUserName($username){




	// build the query
	$q = "SELECT uName FROM Users WHERE username = '$UserName'";



$result = $this->mdb2->query($q)  // ---- This results in a "Using $this when not in object context...." error


	if($result->numRows() >= 1){

			// there is 1 or more hits for a username, it is not available!
		return false;

	} else if ($result->numRows() < 1){

			// there is less than 1 row with that username, we're golden!
		return ture;

	}

}

 

 

when i try to access the $mdb2 object set up in the constructor with the $this-> pointer, i get an error about $this not being in the context of an object.

 

How can this be?  the function i am working in is within the same class definition as the __construct() function

Link to comment
Share on other sites

:-[

 

^  That.  about 100000 times.

 

 

Yes, there is a reason, and it is a very bad one.  Coding w/o little sleep.  That and the function i am having this issue with started out as a copy / paste of another function in the same class that *is* and *needs to be* static.

 

In copying/pasting/not thinking (i was lazy and tired) to save my self mere seconds, i created a 2 hour time suck.

 

Thanks for helping me realize i am a bit of an idiot :)!

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.