In a class in PHP, methods and properties with the static keyword are called static methods and static properties, so that methods and properties can be accessed directly through the class, without having to access the instance of the class, accessing static variables and static properties in the class. You can use the Self keyword and the static keyword, and the two access methods seem to have no difference, but actually it's not the same.
Abstract classperson{ Public Static $_classname= ' Person '; Public Static functionGetintro () {return' This was a person '; } Public functionsay () {returnSelf::Getintro (); } Public functionStaticsay () {return Static::Getintro (); } Public functionGetClassName () {returnSelf::$_classname; } Public functionStaticgetclassname () {return Static::$_classname; }}classDriverextendsperson{ Public Static $_classname= ' Driver '; Public Static functionGetintro () {return' This is a Driver '; }}$temp=NewDriver;Echo $temp->getclassname (). ' <br> ';Echo $temp->say (). ' <br> ';//StaticEcho $temp->staticgetclassname (). ' <br> ';Echo $temp->staticsay (). ' <br> ';
The result after the run is:
Person
This was a person
Driver
This is a Driver
As a result, when static methods and static variables are accessed using the Self keyword in a class, self is parsed into a class that defines methods and variables, and static refers to the called class when accessed using the static keyword.
Add the method print to the abstract class for printing an instance of a class:
Abstract classperson{ Public Static $_classname= ' Person '; Public Static functionGetintro () {return' This was a person '; } Public functionsay () {returnSelf::Getintro (); } Public functionStaticsay () {return Static::Getintro (); } Public functionGetClassName () {returnSelf::$_classname; } Public functionStaticgetclassname () {return Static::$_classname; }//Print method for printing an instance of a class Public function Print() { Print_r(NewSelf ()); }}$temp=NewDriver;$temp-Print();
The "cannot instantiate abstract class person" error is reported after running because the $temp->print () method in this case refers to the class of the defined person, and the abstract class cannot be instantiated. At this point, change the method to:
Public function Print () { print_r(newstatic());}
To run successfully, output driver Object (), indicating that the instance printed at this time is an instance of the driver class
The difference between the PHP static keyword and the self keyword