Why self::function() and $self->variable or self::$variable even though there is $this->function() and $this->variable (PHP)?

StackOverflow https://stackoverflow.com/questions/1700969

  •  19-09-2019
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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