05-13-2009, 05:55 PM
|
#3 (permalink)
|
|
The Gregarious
Join Date: Feb 2009
Location: New York
Posts: 645
Thanks: 64
|
Quote:
Originally Posted by xenon
You've got it somewhat right, but not fully. $this only refers to the current instance of an object created from a class. So, given the following simple class:
Code:
class SimpleClass
{
public $var1 = 'my first variable';
}
$object1 = new SimpleClass();
echo $object1->var1; // outputs 'my first variable'
$object2 = new SimpleClass();
$object2->var1 = 'the second one';
echo $object2->var1; // outputs 'the second one'
echo $object1->var1; // still outputs 'my first variable'
Note that the code above is not optimized, it's only used for demonstration purposes.
Now, you can see that we transform the $var1 public member (that's the name of class variables). In each case, we have a 'separate' $this variable at the class level (inside it), that is tied to each object you create from that class. $this is a special variable referring to "the current object". And that's really what it is...so you don't have to create instances of the class you're writing inside the very same class. Instead, you're only programming a prototype of an object, customizing each instance as you need. $this, however, is not available outside a class (as you've probably already seen), because then it would loose its meaning.
I hope I've been clear enough. If not, feel free to ask questions, and you will be answered  Keep up the good work 
|
Thanks Xenon,
Makes perfect sense. I had not even thought about that. At my level, I'm only thinking about one instance of a specific class, but it's good to remember that $this-> refers to it's own instance. I suppose you can call it an "instance" property of the class, the same way regular properties and methods are considered.
I'd hate to see how confused I get when having to deal with multiple instances of the same class...I hope that's not something that happens too often and only used in books and examples...
|
|
|
|