PHP is an object-oriented class that uses several key words in $this,static,final,const,self.

Source: Internet
Author: User
Tags access properties getcolor php class

the role of this,self,parent three keywords in phpthis,self,parent The difference between the three keywords, which is literally better understood, refers to this, self, and father respectively. Let's start with a few concepts, where are the three key words used? Let's begin by explaining that thisis a pointer to the current object (Let's take a look at the pointer in c), and selfis a pointer to the current class. Parent is a pointer to the parent class . We frequently use pointers to describe them, perhaps because there is no better language to express them.
<?php<span style= "color: #ff0000;"           >//This is a pointer to the current object </span>class test_this{private $content;//define Variable function __construct ($content) {//define Constructor    $this->content= $content; } function __destruct () {}//definition destructor function printcontent () {//define print function Echo $this->content. '    <br/> '; }} $test =new test_this (' Beijing welcomes you! '); Instantiate object $test->printcontent ();//Welcome to Beijing! $test =new test_this (' New Year! ');//Once again instantiate the object $test->printcontent ();//New Year atmosphere! echo ' <br/> '; <span style= "color: #ff0000;" >//self is a pointer to the class itself, only related to the class, regardless of any object instance </span>class test_self{private static $first _count;//define static variable private $last _c    Ount; function __construct () {$this->last_count=++self:: $first _count;//directly assigns a value to another variable with the value of the self Call variable} function __destru    CT () {} function print_self () {print ($this->last_count); }} $abc =new test_self ();//Instantiate Object $abc->print_self ();//1echo ' <br/> '; <span style= "color: #ff0000;" >//parent is a pointer to the parent class </span>class Test_parent{//base class public $name;    Define name the parent class member needs to be defined as public before it can be invoked directly in the inheriting class.    function __construct ($name) {$this->name= $name;    }}class Test_son extends test_parent{//derived classes inherit test_parent public $gender;//define gender public $age; Defines the age function __construct ($gender, $age) {//The constructor parent::__construct (' Nostop ') of the inheriting class, or the constructor of the parent class using parent, to perform the actual        The $gender of $this->gender= are instantiated;    $this->age= $age; } function __destruct () {} function Print_info () {echo $this->name. ' is a '. $this->gender. ', this year '. $this->ag E. ' Old '. '    <br/> '; }} $nostop =new Test_son (' Female ', ' 22 ');//Instantiate Test_son object $nostop->print_info ();//execute output function nostop is a female, 23 years old this year?>

$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 uses such as:
$this-Properties
$this-Way
Examples are as follows:
View Code Printing
<span style= "FONT-SIZE:14PX;" ><?phpclass myclass{private $name;p ublic  function __construct ($name) {$this->name= $name;} Public Function GetName () {return $this->name;} Public  function Printname () {echo $this->getname ();}} $myclass = new MyClass ("I Like PHP"), $myclass->printname ();//output: I like php?></span>
There are three ways to invoke the properties and methods of the current class within a class, namely, self, parent, $this, and the three keywords differ from the following: Self is used to point to the current class, and the parent is used to point to the parents of the current class, which can be used to invoke the properties and methods of the parent class; This is used to invoke its own properties and methods inside the class.
StaticThe keyword can be the class name of the self (used when a static member is called Inside a Class) (used when calling static members inside a class outside of the class)
declare a static variable as follows:
static $val = ';
A variable that exists only in the scope of a function, the value of the variable is not lost after the function is executed, it is initialized only once, the initialization of the static variable cannot use the expression, and the global variable is not replaced because the global variable is accessible by all functions easily resulting in maintenance inappropriate.
in theThere are two main purposes for using static in a class, defining static members, and defining static methods. Static members retain only one variable value, which is valid for all instances, as follows:
<?phpclass myobject{public static $myStaticVar =0;function MyMethod () {self:: $myStaticVar +=2;echo self::$ Mystaticvar;}} $instance 1=new MyObject (); $instance 1->mymethod (); $instance 2=new MyObject (); $instance 2->mymethod ();// Results will be printed separately 2, 4
<?phpclass book{static $num =0;public function showMe () {echo "You are dripping". Self:: $num. " A visitor "; Self:: $num + +;}} $book 1=new Book (), $book 1->showme (), echo "<br>", $book 2=new Book (), $book 2->showme (); echo "<br>"; echo "You are dripping". Book:: $num. " Visitors ";? >
The result will be:
you are a drop of 0 guests
you are a drop of 1 guests
you are a drop of 2 guests
It is also important to note that if the method of the class is static, the property that he accesses must also be static.
FinalThe final class and method cannot be inherited, and the method of the keyword adornment cannot be overridden. The general usage is as follows:
<?phpfinal class myclass{//This class will not be allowed to inherit the final function fun1 () {...} This method will not be allowed to be overridden}
Constin the class'swhen an internal method accesses a property that has been declared as const and static, it needs to use the self:: $name form Call. Examples are as follows:
<?phpclass clss_a{private static $name = "Static Class_a", const pi=3.14, public $value, public static function GetName () {return self:: $name;}  This is incorrect, the static method cannot access the non-static property public static function GetName2 () {return self:: $value;} public Function Getpi () {return self::P i; }}
Note the declaration format for the const attribute is const pi=3.14 instead of const $PI = 3.14.
Selfself represents the class itself, pointing to the current class. Typically used to access static members, methods, and constants of a class. in PHP::,, self, $this operator differencesWhen accessing a member variable or method in a PHP class, if the referenced variable or method is declared as const (defining a constant) or static (declaring static), then the operator must be used::, conversely, if the referenced variable or method is not declared as const or static, Then you must use the operator---.
In addition, if To access a const or static variable or method from within a class, you must use self-referencing , and conversely, if access from within the class is not a const or static variable or method, then the self-referenced $this must be used.
php double colon:: Usagethe double-colon operator , the scope-scoped operator, scope Resolution Operator can access properties and methods overridden in static, const, and class .
Used outside of the class definition, called with the class name. In PHP 5.3.0, you can use variables instead of class names. program List: Use variables to access outside the class definition.
<?phpclass Fruit {    const Const_value = ' Fruit Color ';} $classname = ' Fruit '; Echo $classname:: Const_value; As of PHP 5.3.0echo fruit::const_value;? >
Program List: Used outside the class definition::
<?phpclass Fruit {    const Const_value = ' Fruit Color ';} Class Apple extends fruit{public    static $color = ' Red ';    public static function Doublecolon () {        echo parent::const_value. "\ n";        echo Self:: $color. "\ n";    }}
program Run Result: Fruit Color Red
Program List: Calling the parent method
<?phpclass fruit{    protected function Showcolor () {        echo "fruit::showcolor () \ n";    }} Class Apple extends fruit{    //Override parent ' s definition public    function Showcolor ()    {        //But Still call the parent function        Parent::showcolor ();        echo "Apple::showcolor () \ n";    }} $apple = new Apple (); $apple->showcolor ();? >
Program Run Result:
Fruit::showcolor ()
Apple::showcolor ()
Program List: Using scope qualifiers
  <?php    class Apple    {public        function Showcolor ()        {            return $this->color;        }    }    Class Banana    {public        $color;        Public function __construct ()        {            $this->color = ' Banana is yellow ';        }        Public Function GetColor ()        {            return apple::showcolor ();        }    }    $banana = new Banana;    echo $banana->getcolor ();? >
Program Run Result: Banana is yellowProgram List: Methods for calling base classes
    <?phpclass fruit{    static function color ()    {        return ' color ';    }    static function Showcolor ()    {        echo ' show '. Self::color ();    }} Class Apple extends fruit{    static function color ()    {        return ' red ';    }} Apple::showcolor ();//output is "Show Color"!? >
Program run Result: Show color




PHP is an object-oriented class that uses several key words in $this,static,final,const,self.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.