静态变量不能通过对象或$ this访问,但静态函数可以通过$ this或PHP中的对象访问

Raj*_*aul 1 php

<?php
class c1
{
  public static function f1()
  {
    return "hello";
  }

  public static $a=10;

  public function f2()
  {
    echo $this->f1(); //prints "hello"
    echo $this->a;//ERROR:Undefined property: c1::$a in C:\wamp\www\class_in_php\example5.php on line 14
  }
}

$obj1=new c1;
$obj1->f2();
?>
Run Code Online (Sandbox Code Playgroud)

为什么我们不能使用$ this或该类的对象访问类的静态变量?但我们可以使用$ this或该类的对象访问该类的静态函数.

这种现象背后的原因是什么?

rid*_*rid 6

您应该使用self::而不是$this->访问静态成员.

原因是$this引用类的当前实例,而静态成员是类本身的一部分,而不是实例的一部分.