PHP $this的用法(附带实例)
在 PHP 中,访问实例成员时,应使用类实例化后的对象访问。如果想在类的方法中访问实例成员,则可以使用特殊变量 $this 实现。
$this 代表当前对象,能够在类的方法中访问实例成员。
下面通过代码验证 $this 是否代表当前对象,示例代码如下:
下面演示 $this 的使用方法,示例代码如下:
$this 代表当前对象,能够在类的方法中访问实例成员。
下面通过代码验证 $this 是否代表当前对象,示例代码如下:
class User { public function check($user) { return $this === $user; } } $user = new User(); var_dump($user->check($user)); // 输出结果:bool(true)上述示例代码的输出结果为 true,表示 $this 就是当前对象。
下面演示 $this 的使用方法,示例代码如下:
class User { public $name = '张三'; // 姓名 protected $phone = '123456'; // 电话 private $money = '5000'; // 存款 public function getAll() { echo $this->name, ' '; echo $this->phone, ' '; echo $this->money, ' '; } } $user = new User(); $user->getAll(); // 输出结果:张三 123456 5000在上述代码中,第 8~10 行代码使用 $this 访问类中的属性。通过输出结果可以看出,在方法中使用 $this 可以直接访问到类中的成员。