search
HomeBackend DevelopmentPHP TutorialPHP 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
phpthisintroduceKeywordsclassmateexistobjectusarticleusageDetailed explanationFor

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
 代码如下 复制代码

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
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
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

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 Article

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools