学无先后,达者为师

网站首页 PHP其他 正文

基础知识,PHP对象中static、$this、self 的区别

作者:L小臣 更新时间: 2023-08-30 PHP其他

1、$this 指当前对象的实例化
t h i s 表 示 对 象 的 引 用 , this 表示对象的引用, thisthis写在类中的非静态方法中, 实例化该类,谁调用该方法(一般是对象调用)$this则表示该对象的引用。

<?php
class Exa {
	public $name;
	public function getName(){
		echo $this->name;
	}
}
$e = new Exa();
$e1 = new Exa();
$e->name = '小张';
$e1->name = '小李';
$e->getName();	// 小张
$e1->getName();	// 小李

$this是指类的实例,实例化的是C类,所以调用C类的方法。

2、self 指向类本身
self 和 this 不同,一般用来访问类中的静态变量和静态方法,也是写在类中的方法。self写在哪个类中则表示该类的引用。

<?php
class Person {
	public static function status(){
		self::getStatus();
	}

	protected static function getStatus(){
		echo 'Person';
	}
}

class Men extends Person {
	public static function getStatus(){
		echo 'Men';
	}
}
Men::status(); // Person

self 写在 Person 类中,所以调用的是 Person 类中的getStatus()方法,输出 Person。

3、static也是指类本身
static 和 self 不同,是那个类调用该方法static就表示那个类。

<?php
class Person {
	public static function status(){
		static::getStatus();
	}

	protected static function getStatus(){
		echo 'Person';
	}
}

class Men extends Person {
	public static function getStatus(){
		echo 'Men';
	}
}
Men::status(); // Men

由于 Men 类调用了方法,static 就是 Men类,所以输出的是 Men,即调用了 Men 类的 getStatus()方法。

原文链接:https://blog.csdn.net/weixin_44888397/article/details/114447234

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新