PHP $this,static,final,const,self and double colons in object-oriented classes: How to use these keywords

Source: Internet
Author: User
Tags access properties getcolor
PHP $this,static,final,const,self and double colons in object-oriented classes: These are some of the key words to use.

The role of this,self,parent three keywords in PHP

This,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.

 This is a pointer to the current objectClass test_this{private $content;//define Variable function __construct ($content) {//define constructor $this->content= $cont    Ent } function __destruct () {}//definition destructor function printcontent () {//define print function Echo $this->content. '
'; }} $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 '
';//self is a pointer to the class itself, which is related only to the class, regardless of any object instanceClass test_self{private static $first _count;//define static variable private $last _count; 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 '
';//parent is a pointer to the parent classClass 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 '. '
'; }} $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
  
   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?>
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 current class. You can use this keyword to invoke the properties and methods of the parent class, $this the properties and methods that are used to invoke itself within the class.

Static

The 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 the There 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:
 
  MyMethod (); $instance 2=new MyObject (); $instance 2->mymethod ();//results will be printed separately 2, 4
 
  ShowMe (); echo "
"; $book 2=new Book (); $book 2->showme (); echo"
"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.

Final

The final class and method cannot be inherited, and the method of the keyword adornment cannot be overridden. The general usage is as follows:
 

Const

in 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:
  Note the declaration format for the const attribute is const pi=3.14 instead of const $PI = 3.14. 

Self

self 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 differences

When 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:: Usage

The double-colon operator is the scope-qualified 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.

 
    
Program List: Used outside the class definition::

   program Run Result: Fruit Color Red


Program List: Calling the parent method

 
     Showcolor ();? >
Program Run Result:
Fruit::showcolor ()
Apple::showcolor ()

Program List: Using scope qualifiers

  
 
     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 yellow

Program List: Methods for calling base classes

    
 
     
Program run Result: Show color




  • 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.