Page 1 of 1

can a class property be declared using $this?

Posted: Wed Nov 11, 2009 7:24 pm
by wizardjoe
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?

Re: can a class property be declared using $this?

Posted: Thu Nov 12, 2009 3:18 am
by sergio-pro
Yes, and you can do it even outside the class scope, like this:

Code: Select all

 
class MyClass {
    function showProp( $name ) {
        echo $this->$name;
    }
}
 
$inst  = new MyClass();
$inst->myString = "qwe";
$inst->showProp( "myString" );
 

Re: can a class property be declared using $this?

Posted: Thu Nov 12, 2009 12:52 pm
by wizardjoe
So, in your example, when does the property actually get declared? On line 4 with echo $this->name? Or on line 9 with $inst->myString? And is the property called $name or $myString?

Finally what's the difference between $this->$name and $this->name, does the first notation produce a property declaration?