Home Backend Development PHP Tutorial Detailed explanation of the differences and usage of this, self, and parent keywords in php

Detailed explanation of the differences and usage of this, self, and parent keywords in php

Jul 08, 2017 am 10:15 AM
parent self this

{一}One of the differences between this, self, parent in PHP this article

Object-oriented programming (OOP, Object Oriented Programming) has now become a basic skill for programmers . Using OOP ideas for advanced programming of PHP is very meaningful for improving PHP programming capabilities and planning web development architecture. After being rewritten, PHP5 has made a big leap in its support for OOP and has become a language with most of the features of an object-oriented language. It has many more object-oriented features than PHP4. What I am mainly talking about here is the difference between the three keywords this, self, and parent. Literally understood, they refer to this, myself, and father respectively. Let me give a preliminary explanation first. This is a pointer to the current object (can be regarded as a pointer in C), self is a pointer to the current class, and parent is a pointer to the parent class. We frequently use pointers to describe here because there is no better language to express it. Regarding the concept of pointers, you can refer to the encyclopedia.
Let’s talk about it based on actual examples.

The code is as follows:

<?php
  classname          //建立了一个名为name的类
 {
    private$name;         //定义属性,私有
    //定义
构造函数
,用于初始化赋值
    function construct( $name )
    {
         $this->name =$name;         //这里已经使用了this指针语句①
    }
    //
析构函数
    function destruct(){}
    //打印用户名成员函数
    function printname()
    {
         print( $this->name);             //再次使用了this指针语句②,也可以使用echo输出
    }
 }
 $obj1 = new name("PBPHome");   //实例化对象 语句③
 //执行打印
 $obj1->printname(); //输出:PBPHome
 echo"<br>";                                    //输出:回车
 //第二次实例化对象
 $obj2 = new name( "PHP" );
 //执行打印
 $obj2->printname();                         //输出:PHP
 ?>
Copy after login

Explanation: The above class uses this pointer in statement ① and statement ② respectively, then at that time Who does this point to? In fact, this determines who it points to when instantiating it. For example, when the object is instantiated for the first time (statement ③), then this points to the $obj1 object at that time. Then when executing the print of statement ②, print( $this- >name ), then of course "PBPHome" is output. In the second instance, print($this->name) becomes print($obj2->name), so "PHP" is output. Therefore, this is a pointer to the current object instance and does not point to any other object or class.
{二}The difference between this, self and parent in PHP Part 2 self

In this article we will explain the usage of self

First of all we have to make it clear that self refers to the class Itself, that is, self does not point to any instantiated object. Generally, self is used to point to static variables in the class. If we use static members in the class (usually using the keyword static), we must also use self to call. Also note that using self to call static variables must use:: (field
operator ), see example.

The code is as follows:

<?php
    classcounter     //定义一个counter的类
    {
        //定义属性,包括一个静态变量$firstCount,并赋初值0 语句①  
        private static $firstCount = 0;
        private $lastCount;
        //构造函数
        function construct()
        {
             $this->lastCount =++self::$firstCount;      //使用self来调用静态变量 语句②
        }
        //打印lastCount数值
        function printLastCount()
        {
             print( $this->lastCount );
        }
    }
  //实例化对象
  $obj = new Counter();
 $obj->printLastCount();                             //执行到这里的时候,程序输出1
 ?>
Copy after login

There are two places to pay attention to here: statement ① and statement ②. We defined a static variable $firstCount in statement ①, and then used self to call this value in statement ②. Then what we call at this time is the static variable $frestCount defined by the class itself. Our static variable has nothing to do with the instance of the following object, it is only related to the class. Then if I call the class itself, then we cannot use this to refer to it, because self points to the class itself and has nothing to do with any object instance. Then the this used earlier calls the instantiated object $obj, so don’t get confused.

That’s it for self. It’s easier to understand with examples. The end of the second chapter.

{三}The difference between this, self and parent in PHP Part 3 parent

In this article we will explain the usage of parent.

First of all, we make it clear that parent is a pointer to the parent class. Generally, we use parent to call the constructor of the parent class. The example is as follows:

The code is as follows:

<?php
 //建立基类Animal
 class Animal
 {
    public $name; //基类的属性,名字$name
    //基类的构造函数,初始化赋值
    public function construct( $name )
    {
         $this->name = $name;
    }
 }
 //定义派生类Person 继承自Animal类
 class Person extends Animal
 {
    public$personSex;       //对于派生类,新定义了属性$personSex性别、$personAge年龄
    public $personAge;
    //派生类的构造函数
    function construct( $personSex, $personAge )
    {
         parent::construct( "PBPHome");    //使用parent调用了父类的构造函数 语句①
         $this->personSex = $personSex;
         $this->personAge = $personAge;
    }
    //派生类的成员函数,用于打印,格式:名字 is name,age is 年龄
    function printPerson()
    {
         print( $this->name. " is ".$this->personSex. ",age is ".$this->personAge );
     }
 }
 //实例化Person对象
 $personObject = new Person( "male", "21");
 //执行打印
 $personObject->printPerson();//输出结果:PBPHome is male,age is 21
 ?>
Copy after login

also contains the usage of this, please analyze it yourself. We pay attention to this detail: the member attributes are all public (public

attributes and methods , accessible to code inside and outside the class), especially those of the parent class. This is for inherited classes to access through this. access. The key point is statement ①: parent::construct("heiyeluren"). At this time, we use parent to call the constructor of the parent class to initialize the parent class. In this way, the objects of the inherited class are assigned the name PBPHome. . We can test it by instantiating another object $personObject1. After printing, the name is still PBPHome. Summary: this is a pointer to an object instance, which is determined when instantiating; self is a reference to the class itself, generally used to point to static variables in the class; parent is a reference to the parent class, Generally, parent is used to call the constructor of the parent class.

The above is the detailed content of Detailed explanation of the differences and usage of this, self, and parent keywords in php. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why NameResolutionError(self.host, self, e) from e and how to solve it Why NameResolutionError(self.host, self, e) from e and how to solve it Mar 01, 2024 pm 01:20 PM

The reason for the error is NameResolutionError(self.host,self,e)frome, which is an exception type in the urllib3 library. The reason for this error is that DNS resolution failed, that is, the host name or IP address attempted to be resolved cannot be found. This may be caused by the entered URL address being incorrect or the DNS server being temporarily unavailable. How to solve this error There may be several ways to solve this error: Check whether the entered URL address is correct and make sure it is accessible Make sure the DNS server is available, you can try using the "ping" command on the command line to test whether the DNS server is available Try accessing the website using the IP address instead of the hostname if behind a proxy

How to use self in Python How to use self in Python May 17, 2023 pm 10:40 PM

Before introducing the usage of self in Python, let’s first introduce the classes and instances in Python. We know that the most important concepts of object-oriented are classes and instances. Classes are abstract templates, such as abstract things like students. , can be represented by a Student class. Instances are specific "objects" created based on classes. Each object inherits the same methods from the class, but its data may be different. 1. Take the Student class as an example. In Python, the class is defined as follows: classStudent(object):pass(Object) indicates which class the class inherits from. The Object class is all

How to access parent class properties in Python? How to access parent class properties in Python? Aug 26, 2023 am 10:17 AM

Inobject-orientedprogramming,inheritanceallowsustocreatenewclassesthatinheritthepropertiesandmethodsofanexistingclass.Thispowerfulconceptenablescodereuse,modularity,andextensibilityinourprograms.Beforedivingintoaccessingparentclassattributes,let'shav

Let's talk about why Vue2 can access properties in various options through this Let's talk about why Vue2 can access properties in various options through this Dec 08, 2022 pm 08:22 PM

This article will help you interpret the vue source code and introduce why you can use this to access properties in various options in Vue2. I hope it will be helpful to everyone!

An article that understands this point and catches up with 70% of front-end people An article that understands this point and catches up with 70% of front-end people Sep 06, 2022 pm 05:03 PM

A colleague got stuck due to a bug pointed by this. Vue2’s this pointing problem caused an arrow function to be used, resulting in the inability to get the corresponding props. He didn't know it when I introduced it to him, and then I deliberately looked at the front-end communication group. So far, at least 70% of front-end programmers still don't understand it. Today I will share with you this link. If everything is wrong If you haven’t learned it yet, please give me a big mouth.

Clever way to use this keyword in jQuery Clever way to use this keyword in jQuery Feb 25, 2024 pm 04:09 PM

Flexible use of this keyword in jQuery In jQuery, the this keyword is a very important and flexible concept. It is used to refer to the DOM element currently being manipulated. By rationally using this keyword, we can easily operate elements on the page and achieve various interactive effects and functions. This article will combine specific code examples to introduce the flexible use of this keyword in jQuery. Simple this example First, let's look at a simple this example. Suppose we have a

What is this? An in-depth analysis of this in JavaScript What is this? An in-depth analysis of this in JavaScript Aug 04, 2022 pm 05:02 PM

What is this? The following article will introduce you to this in JavaScript, and talk about the differences between this in different calling methods of functions. I hope it will be helpful to you!

How to use this method in Java How to use this method in Java Apr 18, 2023 pm 01:58 PM

1. this keyword 1. Type of this: Which object is called is the reference type of that object 2. Usage summary 1. this.data;//Access attribute 2. this.func();//Access method 3.this( );//Call other constructors in this class 3. Explanation of usage 1.this.data is used in member methods. Let us see what will happen if this is not added classMyDate{publicintyear;publicintmonth;publicintday; publicvoidsetDate(intyear,intmonth,intday){ye

See all articles