Not really. I don’t know of a workaround for PHP 5.2, though.

What is the difference between new self and new static?
self refers to the same class in which the new keyword is actually written.

static, in PHP 5.3’s late static bindings, refers to whatever class in the hierarchy you called the method on.

In the following example, B inherits both methods from A. The self invocation is bound to A because it’s defined in A’s implementation of the first method, whereas static is bound to the called class (also see get_called_class()).

  1. <?php
  2. class A {
  3. public static function get_self() {
  4. return new self();
  5. }
  6. public static function get_static() {
  7. return new static();
  8. }
  9. }
  10. class B extends A {}
  11. echo get_class(B::get_self()); // A
  12. echo get_class(B::get_static()); // B
  13. echo get_class(A::get_self()); // A
  14. echo get_class(A::get_static()); // A

再来一个:

  1. <?php
  2. class A {
  3. public function create1() {
  4. $class = get_class($this);
  5. return new $class();
  6. }
  7. public function create2() {
  8. return new static();
  9. }
  10. }
  11. class B extends A {
  12. }
  13. $b = new B();
  14. var_dump(get_class($b->create1()), get_class($b->create2()));
  15. The results:
  16. string(1) "B"
  17. string(1) "B"

分类: web

标签:   php