The difference between self and static in php object-oriented programming_php skills

WBOY
Release: 2016-05-16 09:00:14
Original
2770 people have browsed it

in php object-oriented programming, you will always encounter it

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

  static::func();
 }

 public static function func(){}
}

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:

class car
{
 public static function model(){
  self::getmodel();
 }

 protected static function getmodel(){
  echo "this is a car model";
 }
}

Copy after login

car::model();

class taxi extends car
{
 protected static function getmodel(){
  echo "this is a taxi model";
 }
}

Copy after login

taxi::model();
get output

this is a car model
this is a car model
Copy after login

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();

Copy after login

get output

This is a car model
This is a Taxi model
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 the php5.3 version, there was still a slight difference between static and self. what was the specific difference? 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.

Related labels:
php
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