The "$this->" variable...
Ok so I've been reading a million books to fully understand how $this-> works and I think I've got it. I'll try to explain, I hope I get it right, for the sake of brevity, we have a simple class here:
When the main script instantiates this class and creates the object:
$myClass = new myClass();
Well, $myClass-> and $this-> are basically the same thing. You can access methods/properties the same way.
The only difference is that if a property/method is set to private, then the outside object will have no direct access, but the inside object "$this->" will have access....
And that's pretty much it? Did I get it right?
Are there any other differences between the two that I missed?
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:
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 ^^
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...
|All times are GMT. The time now is 11:13 PM.|
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0