Click to See Complete Forum and Search --> : $this-> question.
vicpal25
11-30-2005, 03:37 PM
As I progress my ways through PHP, I came across a chapter in a book I am reviewing about the "$this->" attribute handler within a function on PHP. I still quite can't understand its purpose. I do understand what is suppost to do within a function and that is to state that a variable is passed an attribute but is that it? What is the benefit of it? Just to identify? Thanks if anyone can clear that up for me.
NogDog
11-30-2005, 04:15 PM
It's used in object-oriented PHP. Not my area of experise (yet), but as I understand it: When used within a method within a class, it means to refer to the following attribute for this instantiation of this class. A simplistic example:
class SimpleClass
{
# member declaration
var $var = 'a default value';
# method declaration
function displayVar() {
echo $this->var; # points to value of var for this instance
}
}
# create an instance of the class called "$test":
$test = new SimpleClass();
# call the method displayVar() for this instance:
echo "<p>" . $test->displayVar() . "</p>\n";
# change the value of var for this instance:
$test->var = "a new, changed value";
# call the method again, seeing the new value:
echo "<p>" . $test->displayVar() . "</p>\n";
vicpal25
11-30-2005, 05:09 PM
www got you. I was really trying to find the functionallity between having a varaible within a function without the $this-> and having it and comparing the output difference..interesting..yeah object oriented programming rocks..
SpectreReturns
12-01-2005, 12:56 AM
$this is a pointer towards the class scope of the current class. By using it you may manipulate classes from inside them.
vicpal25
12-01-2005, 10:58 AM
okay i understand that, but it only refers to attributes of functions within a class right?
NogDog
12-01-2005, 12:23 PM
I believe that within a method definition within a class, $this->var refers to the attribute $var defined as part of the class definition, while just $var would be a variable with a scope local only to that specific method. (So $this-> is sort of analagous to "global" within an user-defined function in non-OO PHP, except it means "global within this class definition".)
vicpal25
12-01-2005, 12:34 PM
Aw, that makes more sense. I was wondering how the value of the variable change if it was outside the function within the class. Thanks! My goal is to truly program object oriented PHP.