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?

 

 

$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.

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?

well i knew it didn't have anything to do with the referencing.  I was thinking more along the lines of it creating it simply because you assign something to it in general (like in your example).  I didn't know you could do that.  I've never done that before...never really had a need to...

I've never done that before...never really had a need to...

 

Or perhaps you know, you should explicitly declare class properties before using them.

 

yeah...that's what I usually do...hence having never done that before and therefore didn't know you could

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.