zoukankan      html  css  js  c++  java
  • php类中的$this,static,const,self这几个关键字使用方法

    本篇文章主要分享一下关于php类中的$this,static,final,const,self这几个关键字使用方法

    $this

    $this表示当前实例,在类的内部方法访问未声明为const及static的属性时,使用$this->value='phpernote';的形式。常见用法如:$this->属性,$this->方法

    <?php
      /**
      * 有关人类
      */
      class Person
      {
        
        private $name='张三';
        public  $sex;
        public function run(){
          return $this->name.'能跑';
        }
        public function length(){
          echo $this->run().'800米';
        }
      }
    
      $person=new Person();
      $person->length();
    ?>
    

    static

    声明及调用静态变量如下:

      <?php
      /**
      * 示例
      */
      class Person
      {
        static  $sex=1;
        public  $name='张三';
    
        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();//输出1
      Person::printQianDao(); //输出2
      $person->printQianDao2();//报错:Using $this when not in object context
      $person->printQianDao3();//报错:Using $this when not in object context
      $person->printQianDao4();//输出“张三”;
      Person::printQianDao4(); //报错1:Non-static method Person::printQianDao4() should not be called statically,报错2:Using $this when not in object context
    
    ?>
    

      

    注意事项:

      1.在静态方法内部,不能使用$this(即在静态方法内部只能调用静态成员);

      2.调用静态成员的方法只能是self::方法名或者parent::方法名或者类名::方法名

      3.在类的外部,调用静态方法时,可以不用实例化,直接类名::方法名

      4.静态方法执行之后变量的值不会丢失,只会初始化一次,这个值对所有实例都是有效的

    const

    定义及调用类的常量如下:

      <?php
      /**
      * 示例
      */
      class Person
      {
        const PI=1;
    
        static function getPi(){
          return self::PI;
        }
    
        static function printPi(){
          echo self::getPi();
        }
      }
      Person::printPi();
    ?>
     

    注意:调用类的成员是self::PI,而不是self::$PI

    self

    self表示类本身,指向当前的类。通常用来访问类的静态成员、方法和常量。

  • 相关阅读:
    高速传输线PCB设计
    带状线和微带线
    资源分配
    异步时钟切换电路
    Mathcad操作tips:2D绘图
    Mathcad操作tips:函数、符号计算
    慢性胃炎注意事项
    Arduino I2C + 三轴加速度计ADXL345
    Arduino SPI + SPI Flash芯片W25Q80BV
    Arduino I2C + 三轴加速度计LIS3DH
  • 原文地址:https://www.cnblogs.com/freelyflying/p/7008072.html
Copyright © 2011-2022 走看看