views:

130

answers:

2

I'm confused about these two keywords and the way to use them in PHP5. I think that "this" is used for instanced objects (not static) while "self" is referring to the object itself, not an instance of it and thus used within static objects. Right?

Now, I believe that the correct use inside a class's static method to call another static variable/method is the following:

self::doSomething();
self::$testVar;

That's true?

However, the following also seems to be possible:

$self->testVar;

Yet, $testVar is static. Why is that?

Also, why is $ used infront of self sometimes and sometimes not, and same question for "this" keyword?

+3  A: 

You're right, self is for static self-references while $this is for instantiated ones. self and $this might appear to work everywhere but consider this:

class A
{
  public static function foo()
  {
    $this->bar();
  }

  public static function bar()
  {
    echo 'foobar!';
  }
}

A::foo(); // Fatal error: Using $this when not in object context

This results in a fatal error because foo() was called statically. It's best to take some time and use them appropriately rather than always using one or the other.

Mike B
Wish I could accept both answers, afraid RC was a bit earlier though. Thanks for the code elaboration too!
Tom
Glad I could help, I hope it cleared things up a bit. I had some trouble understanding the differences myself because PHP is so forgiving with these kinds of things. Oh, and about RC being earlier Mine: 13:26:41 vs RC: 13:28:05 :p
Mike B
Oh sorry, I must've misread.
Tom
+2  A: 

You seem to be understanding this correctly. self:: is used for static members and functions when you do not have an instance of the object available, while the $this-> syntax is used when you do.

So in a static method, you would have to use self:: b/c the static method is just that... static and could be called without an instance of the object being created. (i.e. YourClass::staticFunction()) It is perfectly logical though to use $this->memberVar in a non-static method as the function is being called through an instantiated object. ($yourClass->nonStaticFunction()) Therefore $this actually exists within the context of the function.

RC