Detailed explanation of $this usage in PHP

jacklove
Release: 2023-04-01 10:14:02
Original
19854 people have browsed it

this is a pointer to the current object

<?php

class human{
	
	public $name="李四";
	
	public function eat(){
	
	  echo $this->name,&#39;在吃饭&#39;;
	}
	
	public function test(){
	
	  echo $name,&#39;在吃饭&#39;;
	}
	
}

$li=new human();
echo $li->name;//李四
$li->eat();//李四在吃饭。
/*
和java,c++相比
方法体内想访问调用者的属性,必须用$this
如果不加,则理解为方法内部的一个局部变量.
*/ 

$li->test();//Notice: Undefined variable: name in C:\wamp\www\php\this.php on line 14

/******
从生活中的角度来理解$this
女娲造人时, 造了一个"悔恨"的方法
{
    抓[自己]头发
    抽 [自己] 脸
}
世界上的人那么多, 
悔恨时,抓谁的头发?
抽谁的脸?
张三,李四? 王五? 都不能说明合理的情况
只能理解为"自己"
******/
?>
Copy after login

Detailed explanation of $this usage in PHP

This article explains in detail the usage of $this in PHP. For more related content, please pay attention to php Chinese website.

Related recommendations:

The relationship between Java and PHP

##Summary of practical experience with PHP

Related summary of ThinkPHP

The above is the detailed content of Detailed explanation of $this usage in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template