Home Backend Development PHP Tutorial A detailed explanation of the differences between this, self, and parent in PHP_PHP Tutorial

A detailed explanation of the differences between this, self, and parent in PHP_PHP Tutorial

Jul 21, 2016 pm 03:07 PM
parent php self this one the difference Discuss of Detailed explanation

{一}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. Here I am mainly talking about the difference between the three keywords: this, self and parent. Literally understood, it refers 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.

Copy code The code is as follows:

classname //Created a class named name
{
private$name; //Define attributes, private
//Define constructor for initialization assignment
function __construct( $name )
{
$this-> ;name =$name; //This pointer statement has been used here ①
}
//Destructor
function __destruct(){}
//Print user name member function
function printname()
                                                                                                                                                                                                                                             . new name("PBPHome"); //Instantiation object statement ③
//Perform printing
$obj1->printname(); //Output: PBPHome
echo "
"; //Output: Enter
//Second instantiation of the object
$obj2 = new name( "PHP" );
//Perform printing
$obj2->printname(); //Output: PHP
?>




Explanation:

The above class uses this pointer in statement ① and statement ② respectively, then Who was this pointing to at that time? 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. {2} 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 need to be clear that self points 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 symbol), see example.

Copy code
The code is as follows:

classcounter //Define a counter class
{
//Define attributes, including a static variable $firstCount, and assign an initial value of 0 Statement ①
private static $firstCount = 0;
private $lastCount;
//Constructor function
function __construct()
{
lastCount =++self::$firstCount; //Use self to call the static variable statement ②
}
}
}
//Instantiate the object
$obj = new Counter();
$obj->printLastCount(); >


There are two places to pay attention to here, sentence ① and sentence ②. 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.


{3} The third difference between this, self and parent in PHP parent article


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:
Copy code

The code is as follows:
//Create the base class Animal class Animal
{
public $name; //Attributes of the base class, name $name
//Constructor of the base class, initialization assignment
public function __construct( $name )
{
                                                                                          using using using  -                                                                                                       ’ ’ s ’ s ’ s ’ ’ s use to ward through so so so so so so so so so so so out out out out out out out out out out out out out out out out out of         and                  out. $personSex; //For derived classes, newly defined attributes $personSex gender, $personAge age
public $personAge;
//Constructor of derived classes
function __construct( $personSex, $personAge)
{
parent::__construct( "PBPHome"); // Use parent to call the constructor statement of the parent class ①
$this->personSex = $personSex;
$this-> personAge = $personAge;
}
//Member function of the derived class, used for printing, format: name is name, age is age
function printPerson()
{
print( $ this->name. " is ".$this->personSex. ",age is ".$this->personAge );
}
}
//Instantiate the Person object
$personObject = new Person( "male", "21");
//Perform printing
$personObject->printPerson();//Output result: PBPHome is male,age is 21
?>


It 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. 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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327492.htmlTechArticle{一}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 PHP...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

How to set password protection for export PDF on PS How to set password protection for export PDF on PS Apr 06, 2025 pm 04:45 PM

Export password-protected PDF in Photoshop: Open the image file. Click "File"> "Export"> "Export as PDF". Set the "Security" option and enter the same password twice. Click "Export" to generate a PDF file.

Explain strict types (declare(strict_types=1);) in PHP. Explain strict types (declare(strict_types=1);) in PHP. Apr 07, 2025 am 12:05 AM

Strict types in PHP are enabled by adding declare(strict_types=1); at the top of the file. 1) It forces type checking of function parameters and return values ​​to prevent implicit type conversion. 2) Using strict types can improve the reliability and predictability of the code, reduce bugs, and improve maintainability and readability.

How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) Apr 08, 2025 am 12:03 AM

In PHP, the final keyword is used to prevent classes from being inherited and methods being overwritten. 1) When marking the class as final, the class cannot be inherited. 2) When marking the method as final, the method cannot be rewritten by the subclass. Using final keywords ensures the stability and security of your code.

Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Apr 05, 2025 pm 01:03 PM

The necessity of registering VueRouter in the index.js file under the router folder When developing Vue applications, you often encounter problems with routing configuration. Special...

See all articles