This article focuses on the use of several key words about $this,static,final,const,self in PHP classes
$this
$this represents the current instance, using $this->value= ' phpernote ' in the form of an internal method of the class that accesses an attribute that is not declared as const and static. Common usages such as: $this, Properties, $this--method
<?php /** * About Human * * class person { private $name = ' Zhang San '; Public $sex; Public Function Run () { return $this->name. ' can run '; } Public function Length () { echo $this->run (). ' 800 m '; } } $person =new person (); $person->length ();? >
Static
Declare and invoke static variables as follows:
<?php /** * Example */ class person { static $sex =1; Public $name = ' Zhang San '; static function Qiandao () { return self:: $sex + +; } static function Printqiandao () { echo Self::qiandao (); } static function PrintQianDao2 () { echo $this->qiandao (); } static function PrintQianDao3 () { echo $this->name; } Public Function PrintQianDao4 () { echo $this->name; } } $person =new person (); $person->printqiandao ();//Output 1 person ::p Rintqiandao ();//Output 2 $person->printqiandao2 ();//Error: Using $this when "not" in object context $person->printqiandao3 ();//error: Using $this when not in object context $perso N->printqiandao4 ();//output "Zhang San"; Person::p RintQianDao4 (); Error 1:non-static method Person::p RintQianDao4 () should not be called statically, error 2:using $this when not in object context ?>
Precautions:
1. Inside a static method, you cannot use $this (that is, only static members can be called inside a static method);
2. The method to invoke a static member can only be self:: Method name or Parent:: Method Name or Class Name:: Method Name
3. Outside of the class, when a static method is called, it can be used without instantiation, direct class Name:: Method Name
4. After the static method executes, the value of the variable is not lost, it is initialized only once, and the value is valid for all instances
Const
The constants for defining and invoking classes are as follows:
<? PHP /* * * Example * * * class person { constPI =1; Static function getpi () { return self::PI; } Static function printpi () { echo self::getpi (); } } Person::printpi ();? >
Note: The member of the Calling class is self::P I, not self:: $PI
Self
Self represents the class itself, pointing to the current class. Typically used to access static members, methods, and constants of a class.
$this,static,const,self in the PHP class how to use these keywords