Home > Backend Development > PHP Tutorial > PHP object-oriented $this-> usage brief description

PHP object-oriented $this-> usage brief description

巴扎黑
Release: 2023-03-07 11:56:01
Original
7271 people have browsed it

In a member method, the method of calling a member method is the object name plus the method name, and the format is "object name->method name". But when defining a class, we often don't know what the object name is, so we can't use the object name. At this time, we have to use the pseudo variable $this.

What is $this?

$this means itself. There is a pointer in $this. Whoever calls it points to whoever calls it. It can only be used inside the class.

$this usage example:

Let’s give an example so that everyone can see the meaning of $this more clearly.

<?php
header("content-type:text/html;charset=utf-8");
class Preson{                                                //定义类
  public $name;
  public $age;
  public function __construct($Name,$Age)        //构造函数
  {
     $this -> name = $Name;
     $this -> age = $Age;
     echo &#39;<pre class="brush:php;toolbar:false">&#39;;
     var_dump($this);                  //打印出$this
  }
  public function showInfo(){             //成员方法
     echo "个人信息:";
     echo &#39;<br/>&#39; . "名字是:" . $this -> name . &#39;<br/>&#39; . "年龄是:" . $this -> age;
  }
}
$preson = new Preson("小草",25);           //实例化
var_dump($preson);                    //打印出$this
$preson -> showInfo();
echo &#39;<hr>&#39;;
$preson = new Preson("大树",30);           //实例化
var_dump($preson);                   //打印出$preson
$preson -> showInfo();
Copy after login

PHP object-oriented $this-> usage brief description

From the picture above we can see the comparison of results. The printed results of $this and $preson are the same. That is to say, $preson calls $this and $this points to it, so the results are the same. Therefore, where $this points to is determined by the object being instantiated, and is a pointer to the current object instance. This includes variables and methods. This also confirms what we said above. Whoever calls it will point to it.

The above is the detailed content of PHP object-oriented $this-> usage brief description. For more information, please follow other related articles on the PHP Chinese website!

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