Jump to content

$this -> or $a->attribute


lilman

Recommended Posts

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;

    }

}

Link to comment
https://forums.phpfreaks.com/topic/61925-this-or-a-attribute/
Share on other sites

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?

Link to comment
https://forums.phpfreaks.com/topic/61925-this-or-a-attribute/#findComment-308316
Share on other sites

"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.)

Link to comment
https://forums.phpfreaks.com/topic/61925-this-or-a-attribute/#findComment-308333
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.