Solved

Having trouble understanding the concept of $this. I've searched for several explanations, and none clarify the concept for me.

Posted on 2014-07-24
21
120 Views
Last Modified: 2014-07-31
Having trouble understanding the concept of $this. I've searched for several explanations, and none clarify the concept for me.

I don't understand its purpose and why its used.
0
Comment
Question by:LB1234
  • 10
  • 9
  • 2
21 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
In a class definition, there are some variables that should be encapsulated strictly inside one method of the class, but there are other variables that should be shared between methods of the class. These sharable variables are called "properties."  To create one of these sharable properties, you use the pseudo-variable $this-> and append a name to it.
http://php.net/manual/en/language.oop5.basic.php
http://php.net/manual/en/language.oop5.visibility.php
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 450 total points
Comment Utility
Please see http://iconoun.com/demo/temp_lb1234.php

<?php // demo/temp_lb1234.php
ini_set('display_errors', TRUE);
error_reporting(E_ALL);
echo '<pre>';

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28483126.html

// DEFINE A SIMPLE CLASS
Class Thing
{
    // THE CLASS CONSTRUCTOR RUNS WHEN THE CLASS IS INSTANTIATED
    public function __construct($x)
    {
        // ASSIGN THE VALUE OF $x TO A CLASS PROPERTY (BY DEFAULT "PUBLIC")
        $this->x = $x;

        // MODIFY THE VARIABLE, BUT THIS DOES NOT MODIFY THE CLASS PROPERTY
        $x = $x + 3;
    }

    // THE show() METHOD WILL TELL US THE VALUE STORED IN THE CLASS PROPERTY
    public function show()
    {
        echo $this->x;
    }

    // THE oops() METHOD WILL NOT BE ABLE TO FIND THE $x VARIABLE
    public function oops()
    {
        echo $x;
    }
}

// USE THE CLASS
$a = new Thing('THIS IS "A"');
$b = new Thing("B");

// SHOW THE CLASS PROPERTIES
var_dump($a, $b);
echo PHP_EOL;

// USE THE CLASS
$a->show();
echo PHP_EOL;

$b->oops();
echo PHP_EOL;

Open in new window

HTH, ~Ray
0
 
LVL 1

Author Comment

by:LB1234
Comment Utility
Thanks Ray.  What thing or entity does $this represent?  Since it is a variable it must stand for some other thing.  What is that thing?  What could I use in place of $this, if anything?
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
It's more of a language construct than a "thing."  Just like we use the word "Class" to define a class in PHP, we use the word "$this->" as a prefix to a variable name when we want that variable to become a property of the object.
0
 
LVL 82

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 50 total points
Comment Utility
I don't understand it but here are two pages from PHP.net that talk about $this:
http://php.net/manual/en/language.oop5.basic.php
http://php.net/manual/en/language.oop5.properties.php
0
 
LVL 1

Author Comment

by:LB1234
Comment Utility
"as a prefix to a variable name when we want that variable to become a property of the object."

In the sentence above, which object are you referring to?
0
 
LVL 1

Author Comment

by:LB1234
Comment Utility
Dave, unless the concept is already pretty straightforward, I find it's very rare that php.net is a source of clarification.  I looked at their explanation many times before posting my question at EE.  Whoever pens that stuff is clearly a great programmer, but an awful communicator, especially considering that the site, i'm guessing, is intended to help clarify concepts for new programmers PHP as well as being a handy reference for those who've largely mastered it.

There's something to be said for being economical in your wording, but I find PHP.net to actually be terse.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
I understand... but it's still better than most sites for languages.  I'm not sure there is anything 'straightforward' about OOP.
0
 
LVL 1

Author Comment

by:LB1234
Comment Utility
Ray, ok, I'm sort of putting together my understanding of this piece by piece.  Let me see if I have this right so far. $this is only used with methods, and it's purpose is not itself to be a variable but to identify a variable in the class as a property of that class?  

But aren't the variables in question ALREADY properties of that class by having been placed within the classes curly braces?
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 450 total points
Comment Utility
$this is only used with methods, and its purpose is not itself to be a variable but to identify a variable in the class as a property of that class?
Yes, exactly.  And don't feel bad about having to take object-oriented programming in baby steps.  We all have to do that.  It's a completely different way of thinking about problem solving, complete with its own design paradigms, terminology and special programming constructs.

But aren't the variables in question ALREADY properties of that class by having been placed within the classes curly braces?
This slightly misses the point, so let me try to explain a bit more.  Let's say you're a procedural (sometimes called "functional") programmer.  In that world we know about variables in the global scope, which is the main PHP script.  We separate these from variables in the function scope, which is the subsets of the PHP script that are written inside function definitions.  You can have $x in the main script and also have $x inside a function.  These variables will not collide and overwrite each other because they exist in different scope.
http://php.net/manual/en/language.variables.scope.php

Now let's look at object-oriented programming, where the data and programming are organized together into classes.  The class is a blueprint for an object.  When the object is created, we call that "instantiation" and the object that we created is called an "object instance" of the class.  You can think of each object having its own variable scope, and you would be mostly right.  But here is the key difference.  There are no variables in a class definition unless they are defined inside a method of the class.  So if you define $x inside one method and define $x inside another method, you get two separate variables.  

It would be unwieldy to have to pass all of the class variables around in the method calls, but that is what you would have to do, since there are no variables permitted outside of a method.  This leads us to the concept of "properties" which are available to all of the methods of a class.  To show that these are class properties, and not local variables, we use $this-> as the prefix for the variables' names.  When we use $this-> we magically make the resulting variables into class properties and they become available ("visible") to any other method that uses $this-> as a prefix to the same variable name.

It's easier to see this in code than it is to describe it.  Have a look at this article and see if it helps.
http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/A_2626-Beginning-Object-Oriented-Programming-in-PHP.html
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Author Comment

by:LB1234
Comment Utility
Ray, thanks a million for taking the time write all of that out.  I appreciate it, and finally I understand it now.  I guarantee this is the most indepth explanation on the internet that's easily available, because I googled for a few hours before finally posting to EE.  It's really amazing how much other descriptions have left out!!
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Thanks for your kind words.

Now here is an important follow-on message.  You will make this mistake; you cannot avoid it.  We all make this mistake.

You will forget to use $this-> at some point in your life.  When you do, an object property will go missing, and instead you will just have a local variable.  And things will not work well, usually resulting in a run-time error.

Now that you are aware that you will make this mistake, you can be on the lookout for it!

Best regards, ~Ray
0
 
LVL 1

Author Comment

by:LB1234
Comment Utility
Thanks again, Ray, so let me expand on my previous understanding of $this (while hopefully not going off the rails regarding my current understanding).  To mix concepts for a moment -- $This is basically a form of automatically passing arguments to the method being called?
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 450 total points
Comment Utility
That's pretty close.  Technically, $this-> is a reference to the calling object.  Consider the concept of a "person" class, where one of the properties is the person's ZIP code.  You might have several instances (objects) made from this class definition, and these persons could be from anywhere.  Each person would have her own ZIP code, and the internal reference to the ZIP code property in the class might be something like this:

$this->zip

Imagine a method that used a geocoder to determine the location of that ZIP code.  Instead of having to call an external function, the geolocator() method could be built right into the class definition, and it would be called with something like this:

$this->geocode = $this->geolocator();

In this case, the second $this-> tells us that the geolocator() method is to be found in the current instance of the object.  Since the geolocator() method has access to all of the object properties, it would not have a need for us to pass in the ZIP code; it could use $this->zip directly.  An example of how this might be helpful would be a setzip() method.  When the setzip() method is called, the zip property is set and the geolocator() method is called immediately.  Poof!  Now your object has its own $this->geocode property that can be used in mapping applications and it only required one action -- calling the setzip() method.

<?php // demo/temp_lb1234.php
ini_set('display_errors', TRUE);
error_reporting(E_ALL);
echo '<pre>';

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28483126.html

// DEFINE A SIMPLE CLASS
Class Thing
{
    // THE CLASS CONSTRUCTOR RUNS WHEN THE CLASS IS INSTANTIATED
    public function __construct()
    {
        // ASSIGN AN EMPTY VALUE TO THE ZIP CODE
        $this->zip = NULL;
    }

    public function geolocator()
    {
        $this->geocode = /* SIMULATE A GEOCODE LOOKUP USING */ $this->zip;
    }

    public function setZIP($x)
    {
        $this->zip = $x;
        $this->geolocator();
    }
}

$a = new Thing();
$a->setzip('22101');

Open in new window

In some respects, $this-> creates a "global" state within the object, so that all property and method references that are resolved through $this-> are available to all methods inside the object.

More fun reading here (follow the links, and don't be bashful about posting your questions to E-E).
http://php.net/manual/en/language.oop5.php
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Footnote: I just tested and $this-> is case-sensitive.
0
 
LVL 1

Author Comment

by:LB1234
Comment Utility
Howdy Ray, I'm really starting to get this!

I tried the following code, but got unexpected results. I was expecting 6 and 8 to be returned but I got 2 and 4 with an error message saying, Notice: Use of undefined constant wheels - assumed 'wheels':

<?php

class Car {
	
	public $doors;
	public $wheels;
	
	public function add() {
		echo $this->doors + wheels;
			
	}

	
}

$sports_car = new Car;
$hatchback = new Car;

$sports_car->doors = 2;
$sports_car->wheels = 4;

$hatchback->doors = 4;
$hatchback->wheels = 4;

$sports_car->add();
$hatchback->add();
?>

Open in new window

0
 
LVL 1

Author Comment

by:LB1234
Comment Utility
Oh oops, I forgot to preface "wheels" with $this->

Ok Ray I finally got the concept.  Really, thanks so much for the example code and links and explanations.  I appreciate it incredibly.  Really.

Have a good one.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Oh oops, I forgot to preface "wheels" with $this->

Ha!  Yes, we all do that.  You will do it a few more times, too, if you're anything like me.  But at least now you've seen the symptom and found the issue fairly quickly.

Thanks for the points and thanks for using E-E, ~Ray
0
 
LVL 1

Author Comment

by:LB1234
Comment Utility
Lol, it didn't take me very long to do the very thing you'd said we'd all sooner or later forget to do.  I guess it much sooner rather than later. :)
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Yes!  I am a great believer in making lots of mistakes fast.  It's a great way to make progress, just like Edison and lightbulbs.
0
 
LVL 1

Author Comment

by:LB1234
Comment Utility
Ray, I guess I do have more one more question about $this, and it's probably what's throwing a lot of people off about it.  Are you still seeing these comments?
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now