📜  self 和 $this 有什么区别?

📅  最后修改于: 2021-09-14 02:18:59             🧑  作者: Mango

关键字self仅用于在该类的范围内引用当前类本身,而$this用于引用类的特定实例的成员变量和函数。

self运算符: self运算符表示当前类,因此用于访问类变量或静态变量,因为这些成员属于一个类而不是该类的对象。
句法:

self::$static_member

$this运算符: $this,正如“$”符号所暗示的那样,是一个对象。 $this 代表一个类的当前对象。它用于访问类的非静态成员。
句法:

$that->$non_static_member;

在PHP何时在 $this 上使用 self

例子:

PHP
name;
        }
       
        public static function getAge() {
            return self::$age;
        }
          
        public function getStudentAge() {
            return self::getAge();
        }
    }
      
    $obj = new StudentDetail();
  
    $obj->name = "GFG";
  
    StudentDetail::$age = "18";
  
    echo "Name : " .$obj->getName()."\xA";
    echo "Age  : " .StudentDetail::getStudentAge();
  
?>


输出
Name : GFG
Age  : 18

self 和 $this 的区别:

self

$this

The self keywоrd is nоt рreсeded by аny symbоl, we can use it as it is. this keyword should be antecedent with a $ symbol whenever referring to the class members.
In order to access class variables and methods, a scope resolution operator is used. In order to access class variables and methods, an arrow operator ( -> ) is used.
The self keyword is used to access the static members of the class present in the program. $this is used to access the non-static members of the class present in the program.
Self keyword refers to the class members, but doesn’t point toward any particular object of the class.   $this could refer to the member variables and function for a selected instance of the class.