Question

I am trying to teach some friends PHP, and I am getting hung up on trying to explain how $this-> works without technical jargon. I believe once I get them past this understanding, I can actually start to teach them how to code using OOP.

The people which I am teaching understands how to use classes, variables, and how they all interact with each other using extends, the public, private, and protected scope of functions and variables.

The only thing that is holding up them up is explaining $this-> and self:: to them. I try to dumb it down by saying "when you refer to a class variable, you are going to call it in the function using $this->", referring to the class's variable, because we defined it in the class instead of in the function itself.

Is there a better, easier way to explain this to someone who is learning PHP's OOP design?

I have also noticed, once you get advanced into a programming language, you get used to using these methods without thinking about them. For me, it is hard to go back to the basics without using technical jargon to explain how to use these methods.

Was it helpful?

Solution 2

When you have a class - existing object -Example:

class Object
{
     protected $variable;

     public function method($param) {}
}

$this is just a way of telling ME.

For example when you go and start eating you make it like that

ME::getSpoon();
ME::UseSPoonToFetchSoup();
ME::BringSpoonToMouth();
ME::PutSpoonInMouth();
ME::TakeSpoonOut();
ME::Swallow():

And then repeat some of the steps. The ME is reference for YOU yourself. If you think about that - this algorithm is true for almost everyone and each of existing ppl could use it - just remembering that ME is the actual ,,human'' eating soup with the spoon.

Same is for object. In this example if you change the code a bit to

class Object
{
     protected $variable = 0;

     public function method($param = 1) {$this->variable += $param; return $this->variable;}
}

Executing method method(); without parameters would add into object OWN memory place for $variable 1 and then tells you new sum.

$obj1 = new Object();
$obj2 = new Object();

echo "Obj1: " .$obj->method(10).'<br/>'; //this will print 10
echo "Obj2: " .$obj->method(2).'<br/>'; //;this will print 2

This objects must know who they are therefore needs to know the reference for themselves and this is where that $this same for.

A wish this explanation is quite ease and understandable.

OTHER TIPS

You could try something like this:

Every car has fuel ($fuel).

But if you're in your car you don't want to know the fuel of the other cars, you want to know the fuel of your car.

So you go like $this->fuel

I think that this should be simple enough without losing to much of the accuracy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top