Differences between php object-oriented programming self and static _ php skills-php Tutorial

Source: Internet
Author: User
This article describes the differences between the static keyword and the self keyword in PHP. This article describes the definition of the static keyword, LateStaticBindings, and the differences between the static keyword and the self keyword, for more information about php object-oriented programming

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 modelThis is a car model

We can find that self still calls 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 modelThis is a Taxi model

As you can see, when static is called, even if the subclass calls the method of the parent class, the method called in the parent class method will also be the method of the child class (this is a good detour ..)

Before PHP5.3, there was a difference between static and self. what is it? after all, it is a 7 version. I don't know.

In summary, self can only reference methods in the current class, while the static keyword allows the function to dynamically bind methods in the class at runtime.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.