The first is a set of code:
Abstract class user {} class admin extends user {private $ group; public static function create () {return new admin ();} public static function getgroup () {return "admin ";}//....... other functions ..}
Class normaluser extends user {private $ group; public static function create () {return New normaluser ();} public static function getgroup () {return "normaluser ";} // other functions .}
First, an abstract class is defined, and two sub-classes admin and normaluser are created. Both classes contain two static methods: Create and getgroup. such code has almost no problems, but there is a lot of redundancy. Now there are only two subclasses. If the number of subclasses increases, you need to add similar code. In this case, we have to think about whether it is okay to extract this generic code into the parent class.
Many people may think of using the self keyword. Let's get started.
abstract class User{ public static function create(){ return new self(); } public static function getGroup(){ return self::getGroup(); }}class Admin extends User{}class NormalUser extends User{}Admin :: create();
The code looks a lot more regular. Unfortunately, the following error message is displayed when you run this Code:
--------------------------------------------------------------PHP Fatal error: Cannot instance abstract class User in...--------------------------------------------------------------
What is the cause of this error? The reason is that self is resolved to the object (User) defined as create, rather than the object (Admin) that calls self. Therefore, the self method is not feasible.
Sigh ....
But don't be discouraged. php 5.3 introduces the concept of delayed static binding, which is marked with the static keyword. It is similar to the self keyword. The difference is that, static will be parsed as the called class rather than the defined class. Now the code becomes like this:
abstract class User{ public static function create(){ return new static(); } public static function getGroup(){ return static::getGroup();}}
Is it much more convenient?
.....