Jump to content

can a class property be declared using $this?


wizardjoe

Recommended Posts

Hi all,

 

I'm working on an open source project and recently came across a piece of code that I found to be ambiguous. The code is a class definition with a constructor that takes one argument, &$db, which is a reference argument to a variable specifying the database connection. The beginning goes like this:

 

class someClass

{

function someClass(&$db)

{

$this->db = &$db;

}

 

Note that there isn't an explicit declaration of the class variable $db. However all the functions in this class seem to be able to utilize it, through the expression $this->db = somevalue. So my question is does PHP interpret the $this->db statement as an implicit declaration of the variable $db? Or am I missing something here?

 

 

Link to comment
Share on other sites

$this->db is shorthand for a property in the class.  So somewhere in the class (probably at the top) you would have:

 

class someClass
{

// example:
private $db = ''; // that $this->db in the function (method) below points to this $db right here

function someClass(&$db)
{
$this->db = &$db;
}

 

edit: er..I guess I failed to notice you mentioned it not being present... maybe it's declared somewhere below?  Maybe you can declare it like that...if you can, I guess I'll learn something new here too...

 

edit2: ...and I just tested, and apparently you can.

Link to comment
Share on other sites

edit: er..I guess I failed to notice you mentioned it not being present... maybe it's declared somewhere below?  Maybe you can declare it like that...if you can, I guess I'll learn something new here too...

Yes, you can declare properties like that. It doesn't have anything to do with the referencing.

 

class someClass
{
public function __construct($str)
{
	$this->str = $str;
}

public function echoStr()
{
	echo $this->str;
}
}
$something = 'hello';
$instance = new someClass($something);
$instance->echoStr();

 

Would work as well. Or am I misunderstanding the question?

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.