Home php What is the difference between Static, Self and Parent in PHP?

What is the difference between Static, Self and Parent in PHP?

Author

Date

Category

Actually I would like to see the difference in the work with Static :: from Parent :: and Self ::


Answer 1, Authority 100%

Parent – We call the parent method (not necessarily static), self – call the method of this class, static – call the current class method. The difference between Self and Static is clearly visible, for example, when you do new self () or New Static () – In the first case, a class object will be created, where the self is mentioned (i.e., a parent has been created), in the second – the object of the class where the method is called (i.e. descendant)

Examples You can see here . “When to apply” – always, unless you need exactly the current class, not his heirs. I do not know when it may be needed, so you can always use Static, then there will be less problems)

In the documentation you can read this article , there Just described the difference between Static and Self and other

(response is transferred from the comments BOPOH )


Answer 2, Authority 76%

Example of differences “Static ::” from “Self ::”. Create a class ‘Model’ (basic) and child ‘Users’

1) In this case, “Self ::” is in the parent class, therefore takes the data
From the parent (from where it is located).

class model {
  Public Static $ table = 'Table';
  Public Static Function GetTable () {
   Return Self :: $ Table;
   }
  }
Class User Extends Model {
   Public Static $ Table = 'Users';
  }
  Echo User :: GetTable (); // Will 'Table'

2) In this case, “Static ::” takes data from the caller, in our case ‘Users’.

class model {
  Public Static $ table = 'Table';
  Public Static Function GetTable () {
   RETURN STATIC :: $ Table;
   }
  }
Class User Extends Model {
   Public Static $ Table = 'Users';
  }
  Echo User :: GetTable (); // Will 'Users'

3) And here “Parent ::” is used to access the methods and properties of the base (parent) class. Here we, in a subsidiary, overdered
Basic class method (foo ()), but with the help of “Parent ::” can still
Contact your parent method.

class model {
    Public Static $ table = 'Table';
    Public Static Function Foo () {
     Echo "1_Test";
     }
    }
  Class User Extends Model {
      Public Static Function Foo () {
     Echo "2_Test";
     Parent :: foo ();
     }
    }
Echo User :: foo (); // Will out '2_Test1_Test'

Answer 3, Authority 12%

self class in which is written.

static class in which it was executed.

For example, if you cause an inherited method in which Self / Static, then each option will give different results.

Late Static Binding .

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions