Home  >  Article  >  Backend Development  >  The difference between self and static in php object-oriented programming, object-oriented programming self_PHP tutorial

The difference between self and static in php object-oriented programming, object-oriented programming self_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:53:43987browse

The difference between PHP object-oriented programming self and static, object-oriented programming self

In PHP object-oriented programming, you will always encounter

class test{
 public static function test(){
  self::func();

  static::func();
 }

 public static function func(){}
}

But do you know the difference between self and static?

In fact, the difference is very simple. You only need to write a few demos to understand:

Demo for self:

class Car
{
 public static function model(){
  self::getModel();
 }

 protected static function getModel(){
  echo "This is a car model";
 }
}

Car::model();

Class Taxi extends Car
{
 protected static function getModel(){
  echo "This is a Taxi model";
 }
}

Taxi::model();
Get output

This is a car model
This is a car model

You can find that self will still call the method of the parent class in the subclass

Demo for static

class Car
{
 public static function model(){
  static::getModel();
 }

 protected static function getModel(){
  echo "This is a car model";
 }
}

Car::model();

Class Taxi extends Car
{
 protected static function getModel(){
  echo "This is a Taxi model";
 }
}

Taxi::model();

Get output

This is a car model
This is a Taxi model

You can see that when calling static, even if the subclass calls the method of the parent class, the method called in the parent class method will still be the method of the subclass (so confusing...)

Before the PHP5.3 version, there was still a little difference between static and self. What exactly was it? After all, they were all dominated by version 7. I won’t understand it anymore.

The summary is: self can only refer to methods in the current class, and the static keyword allows functions to dynamically bind methods in the class at runtime.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1123781.htmlTechArticleThe difference between PHP object-oriented programming self and static, object-oriented programming self In PHP object-oriented programming, there will always be Encountered class test{ public static function test(){ self::func(); static::...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn