The difference between self and static in PHP object-oriented

WBOY
Release: 2016-07-29 08:51:06
Original
949 people have browsed it

data-id="1190000005060322" data-license="sa">

In PHP object-oriented programming, you will always encounter

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

    static::func();
  }

  public static function func(){}
}</code>
Copy after login

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:

<code>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();</code>
Copy after login

Get the output

<code>This is a car model
This is a car model
</code>
Copy after login

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

Demo for static

<code>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();
</code>
Copy after login

gets the output

<code>This is a car model
This is a Taxi model
</code>
Copy after login

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 PHP5.3, there was still a little difference between static and self. What exactly was it? After all, it was all in version 7. I won’t understand it anymore.

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

Reference

  1. http://www.programmerinterview.com/index.php/php-questions/php-self-vs-static/

The above introduces the difference between self and static in PHP object-oriented, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!