can a class property be declared using $this?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wizardjoe
Forum Newbie
Posts: 2
Joined: Mon Aug 25, 2008 7:09 pm

can a class property be declared using $this?

Post 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?
User avatar
sergio-pro
Forum Commoner
Posts: 88
Joined: Sat Dec 27, 2008 12:26 pm

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

Post 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" );
 
wizardjoe
Forum Newbie
Posts: 2
Joined: Mon Aug 25, 2008 7:09 pm

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

Post 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?
Post Reply