1

What are the different between $this and self in PHP?

While I was reading static keyword on php.net, I got confused with the following sentence.

$this is not available inside the method declared as static.

Why $this is not available while doing so?

Any help will be appreciate!

Thanks!

  • You can also check [this answer](http://stackoverflow.com/questions/1948315/wheres-the-difference-between-self-and-this-in-a-php-class-or-php-method) – MISJHA May 09 '13 at 04:14
  • Take a look at this link http://php.net/manual/en/language.oop5.basic.php – slackmart May 09 '13 at 04:22

3 Answers3

2

$this is used for calling non-static variables and methods.

self is used for calling static variables and methods.

When to use self over $this?

Community
  • 1
  • 1
Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100
0

$this is used to access class's Member Functions and Member Properties which are Non-Static

while

self is used to access Static Members and Static Functions of a class.

One thing to need to remember while working with Static is that Static Members are only accessible by Static Methods and not by other Member Functions (Non-Static) of class.

Smile
  • 2,770
  • 4
  • 35
  • 57
0

Another fun aspect of this is that there is also a static scope that can be used which references the class of the calling class context as opposed to the defined class context. So the code:

class A {
    public static function createNew(){
       return new self();
    }
}

class B extends A {
}

$test = B::createNew(); // This will actually yield an instance of A

but if class A was defined as

class A {
    public static function createNew(){
       return new static();
    }
}    

Then $test = B::createNew(); would yield a instance of B as you would expect.

This is also relevant for static properties, when there is inheritance in play self::$property and static::$property can mean two totally different things.

If inheritance and static properties/methods are in play it is important to know the difference and in my experience self is almost always wrong in these cases and it can lead to some fun bugs that only manifest if the more then one member of the class hierarchy is in play at a given time.

Orangepill
  • 24,500
  • 3
  • 42
  • 63