lilman Posted July 26, 2007 Share Posted July 26, 2007 I know PHP, but found it difficult when first learning it to understand OO. I am giving OO another swing, and I am looking for better explanation than the book is giving me. I have seen '$this->' before, but I have no idea how to read it, what it means, or what it does. If someone could explain it, I'd appreciate it. Here is an example out of my book: class classname { var $attribute; function get_attribute() { return $this->attribute; } function set_attribute($new_value) { $this->attribute = $new_value; } } Quote Link to comment Share on other sites More sharing options...
yarnold Posted July 26, 2007 Share Posted July 26, 2007 If you're referring to the attribute from INSIDE the class, use $this->attribute.. If you're referring to the attribute from the rest of your script (ie not inside the class) then use the variable that you assigned to become an instance of that class.. so in your example, $a->attribute $this-> just "means" that it is referring to an attribute or a method that is inside "this" instance of "this" class. Any better? Quote Link to comment Share on other sites More sharing options...
Wildbug Posted July 26, 2007 Share Posted July 26, 2007 "this" is a generic way of referring to whatever object will be running that code. I'm not sure how versed you are in OOP, but an object is a bunch of values and subroutines that are defined by what class it belongs to -- how it was defined. A class sets up the rules/attributes (properties and methods) that define an object. So each object has its own properties, and when it comes time to run a method (an object's subroutine), the object is generically referred to as "this" in the method. Not the best explanation, probably.... I'll give a small example: class SomeClass { function __construct($a = 0) { $this->value = $a; } function getValue() { return $this->value; } } $MyObject1 = new SomeClass(4); $MyObject2 = new SomeClass(7); echo $MyObject1->getValue; // Output: 4 echo $MyObject2->getValue; // Output: 7 So when $MyObject1->getValue runs, the getValue function uses MyObject1 in place of "this" -- "this" refers to whatever object is running through the code on that particular execution. (See the basics for mo'betta info.) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.