Differences and differences between new static of and new self of in PHP

  • 2021-07-16 01:56:24
  • OfStack

In this paper, the differences between new static () and new self () in PHP are described with examples, which is believed to be helpful for everyone to learn PHP programming.

The cause of the problem is to build a local station. It is found that it can't be built with PHP 5.2, and there are many parts above 5.3 in PHP code, which require changes to run under 5.2.

I found a place instead


return new static($val);

What is this Nima? I've only seen it before


return new self($val);

So I looked up the difference between them on the Internet.

self-This is the class, this is the class in the code snippet.

static-PHP 5.3 adds only the current class, a bit like $this, which is extracted from heap memory and accessed to the currently instantiated class, so static represents that class.

Let's look at the professional explanation of foreigners:

self refers to the same class whose method the new operation takes place in.

static in PHP 5.3's late static bindings refers to whatever class in the hierarchy which you call the method on.

In the following example, B inherits both methods from A. self 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() ).


class A {
  public static function get_self() {
    return new self();
  }

  public static function get_static() {
    return new static();
  }
}

class B extends A {}

echo get_class(B::get_self()); // A
echo get_class(B::get_static()); // B
echo get_class(A::get_static()); // A

This example is basically understood by looking at it.

The principle is understood, but the problem has not been solved. How to solve return new static ($val); What about this question?

In fact, it is simple to use get_class ($this); The code is as follows:


class A {
  public function create1() {
    $class = get_class($this);
      return new $class();
  }
  public function create2() {
    return new static();
  }
}

class B extends A {

}

$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));

/*
The result 
string(1) "B"
string(1) "B"
*/

Interested friends can test the sample code under 1, and I believe there will be new gains!


Related articles: