0

I was watching PHP video lectures . I have user class in my project directory now in tutorial inside a static function its instantiated like this

 private static function  instantiate($result){
 $object = new self;
 //here goes loop 
 }

and somewhere its used like this

$object= new user();

Will someone please guide me about the concept of first case where it says new self

Sikander
  • 2,799
  • 12
  • 48
  • 100

2 Answers2

4

"self" is a keyword that references the current class. It is only available inside the class' code.

You can use it to call methods on your own class, but due to binding you can also use it to call methods on a superclass.

Consider the following example:

class TestA {
  public static function makeNewInstance() {
    return new TestA();
  }
}

class TestB extends TestA {
}

Now, calling TestB::makeNewInstance(); will return an instance of TestA. (TestB inherits the method, but it's linked directly to TestA so will still return that)

Compare with this one:

class TestA {
  public static function makeNewInstance() {
    return new self();
  }
}

class TestB extends TestA {
}

Now, calling TestB::makeNewInstance() will return an instance of TestB. (Since self references the active class, and you're calling it on TestB, the contents of "self" is now TestB instead of TestA.

Hope that explains for you. Otherwise, maybe some more detail in your question would help attract more specific answers.

Erik
  • 3,598
  • 14
  • 29
0

self points to the class in which it is written. Refer What does new self(); mean in PHP?

$object= new user(); // It makes the object of the class user - outside from the user class

Community
  • 1
  • 1
Kiren S
  • 3,037
  • 7
  • 41
  • 69