Home Backend Development PHP Tutorial PHP object-oriented $this keyword usage detailed explanation_PHP tutorial

PHP object-oriented $this keyword usage detailed explanation_PHP tutorial

Jul 13, 2016 am 10:49 AM
php this introduce Keywords classmate exist object us article usage Detailed explanation For

This article will introduce to you students how we often use this keyword in PHP classes. Now I will briefly analyze the usage of $this keyword in object-oriented PHP. I hope this tutorial will be helpful to all students.

We knew earlier that accessing object member properties and methods outside the object is done using references to the object. Within the object, when a member method accesses other member properties or member methods in its own object, it must use a special object reference "$this->value" to access it. Which object the member belongs to, the $this reference represents. Object, and can only be used within member methods of the object.

In order to solve the naming conflict and uncertainty problem of variables and attributes in PHP classes and objects, the "$this" keyword is introduced to call the current object.

When calling the properties and methods of the current object in a class, you must use the "$this->" keyword; $this in the constructor refers to the new object created by the constructor; local variables within the method do not belong to the object. Do not use the $this keyword to obtain the value. Using the $this keyword, we can call object properties or methods in the class.

1. Call variables

Example:

 代码如下 复制代码
class user{
private $n;
function __construct(){
$name="Mike";
echo $this->n=$name;
  }
 }
 $p=new user();
?>

2. Call method

Example:

The code is as follows Copy code
 代码如下 复制代码

class cal{
public function sum($a,$b){
return $a+$b;
}
public function prt($a,$c){
return $a*$c;
}
public function result($a,$b,$c){
$a=$this->sum($a,$b);
   return $this->prt($a,$c);
  }
 }
 $c=new cal();
 echo "(2+3)*10= " .$c->result('2','3','10');
?>

class cal{
public function sum($a,$b){

Return $a+$b;
代码如下 复制代码
class Person{
//下面是人的成员属性
var $name; //人的名子
var $sex; //人的性别
var $age; //人的年龄
//定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值
function __construct($name="", $sex="", $age=""){
$this->name=$name;
$this->sex=$sex;
$this->age=$age;
}
//这个人可以说话的方法, 说出自己的属性
function say() {
echo "我的名子叫:".$this->name." 性别:".$this->sex." 我的年龄是:".$this->age."
";
}
//对象克隆时自动调用的方法, 如果想在克隆后改变原对象的内容,需要在__clone()中重写原本
的属性和方法
function __clone(){
//$this指的复本p2, 而$that是指向原本p1,这样就在本方法里,改变了复本的属性。
$this->name="我是假的$that->name";
$this->age=30;
}
}
$p1=new Person("张三", "男", 20);
$p2=clone $p1;
$p1->say();
$p2->say();
?>
} public function prt($a,$c){ Return $a*$c; } public function result($a,$b,$c){ $a=$this->sum($a,$b); Return $this->prt($a,$c); } } $c=new cal(); echo "(2+3)*10= " .$c->result('2','3','10'); ?> Let's take a look at the following example. What is $this doing?
The code is as follows Copy code
class Person{ //The following are the member attributes of people var $name; //The person’s name var $sex; //Person’s gender var $age; //Age of person //Define a constructor parameter to assign values ​​to the attributes name $name, gender $sex and age $age function __construct($name="", $sex="", $age=""){ $this->name=$name; $this->sex=$sex; $this->age=$age; } //The way this person can speak, tell his own attributes function say() { echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."
" ; } //Method automatically called when an object is cloned. If you want to change the contents of the original object after cloning, you need to rewrite the original object in __clone() Properties and methods of function __clone(){ //$this points to the copy p2, and $that points to the original p1, thus changing the attributes of the copy in this method. $this->name="I am fake $that->name"; $this->age=30; } } $p1=new Person("Zhang San", "Male", 20); $p2=clone $p1; $p1->say(); $p2->say(); ?>

Output of the above example:

Execution results
My name is: Zhang San Gender: Male My age is: 20
My name is: I am the fake Zhang San Gender: Male My age is: 30

Let’s take a look at what $this does in the above code:

1. Access members inside the object, such as $this->name

2. Access other methods of the object, such as accessing the $this->run() and $this->eat("apple") methods outside the say() method.

Another thing worth noting is that local variables and member attributes can have the same name, but their scope and access methods are different. For example, $name in the eat() method body is equivalent to a local variable, and its scope is limited to eat Inside the method, $name in the member attribute declaration part of Person is equivalent to a global variable and can be accessed in other methods using the form $this->name.

Example

The code is as follows
 代码如下 复制代码

< ?php
class UserName
{
//定义属性
private $name;
//定义构造函数
function __construct( $name )
{
$this->name = $name;
//这里已经使用了this指针 

//析构函数 
function __destruct(){}  
//打印用户名成员函数 
function printName() 

print( $this->name );
//又使用了PHP关键字this指针 

}  
//实例化对象 
$nameObject = new UserName
( "heiyeluren" );  
//执行打印 
$nameObject->printName();
 //输出: heiyeluren 
//第二次实例化对象 
$nameObject2 = new UserName( "PHP5" ); 
//执行打印 
$nameObject2->printName(); //输出:PHP5 
?>

Copy code
< ?php

class UserName

{

//Define attributes //Define constructor function __construct( $name ) { $this->name = $name; //This pointer has been used here } //Destructor function __destruct(){} //Print username member function function printName() { print( $this->name ); //The PHP keyword this pointer is used again }
}
//instantiate object $nameObject = new UserName ( "heiyeluren" ); //Execute printing $nameObject->printName(); //Output: heiyeluren //Second instantiation of object $nameObject2 = new UserName( "PHP5" ); //Execute printing $nameObject2->printName(); //Output: PHP5 ?> http://www.bkjia.com/PHPjc/632686.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632686.htmlTechArticleThis article will introduce to students that we will commonly use this keyword in the php class. Below I will briefly explain Analyze the usage of $this keyword in object-oriented php. I hope this tutorial will be helpful to all students...
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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks 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)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles