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?
can a class property be declared using $this?
Moderator: General Moderators
- sergio-pro
- Forum Commoner
- Posts: 88
- Joined: Sat Dec 27, 2008 12:26 pm
Re: can a class property be declared using $this?
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?
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?
Finally what's the difference between $this->$name and $this->name, does the first notation produce a property declaration?