PHP中::、->、self、$this操作符

在访问PHP类中的成员变量或方法时,如果被引用的变量或者方法被声明成const(定义常量)或者static(声明静态),那么就必须使用操作符::,反之如果被引用的变量或者方法没有被声明成const或者static,那么就必须使用操作符->.

另外,如果从类的内部访问const或者static变量或者方法,那么就必须使用自引用的self,反之如果从类的内部访问不为const或者static变量或者方法,那么就必须使用自引用的$this.

$this实例代码如下:

  1. <?php 
  2. // this是指向当前对象的指针 
  3. class test_this{ 
  4.     private $content//定义变量 
  5.      
  6.     function __construct($content){ //定义构造函数 
  7.           $this->content= $content
  8.     } 
  9.     function __destruct(){}//定义析构函数 
  10.      
  11.     function printContent(){//定义打印函数 
  12.         echo $this->content.'<br />'
  13.     } 
  14. $test=new test_this('北京欢迎你!'); //实例化对象 
  15. $test->printContent();//北京欢迎你! 

::使用方法实例代码如下:

  1. //parent是指向父类的指针 
  2. class test_parent{ //基类 
  3.     public $name;  //定义姓名  父类成员需要定义为public,才能够在继承类中直接使用 this来调用. 
  4.     function __construct($name){ 
  5.         $this->name=$name
  6.     } 
  7. class test_son extends test_parent{ //派生类  继承test_parent 
  8.     public $gender;//定义性别 
  9.     public $age;    //定义年龄 
  10.     function __construct($gender,$age){ //继承类的构造函数 
  11.         parent::__construct('nostop');//使用parent调用父类的构造函数,来进行对父类的实例化 
  12.         $this->gender=$gender
  13.         $this->age=$age
  14.     } 
  15.     function __destruct(){} 
  16.     function print_info(){ 
  17.         echo $this->name.'是个'.$this->gender.',今年'.$this->age.'岁'.'<br />'
  18.     } 
  19. $nostop=new test_son('女性','22');//实例化test_son对象 
  20. $nostop->print_info();//执行输出函数  nostop是个女性,今年23岁 

使用self::$name的形式.注意的是const属性的申明格式,const PI=3.14,而不是const $PI=3.14

实例代码如下:

  1. class clss_a { 
  2.       
  3.      private static  $name="static class_a"
  4.       
  5.      const PI=3.14; 
  6.      public $value;     
  7.           
  8.      public static function getName() 
  9.      { 
  10.         return self::$name;     
  11.      } 
  12.      //这种写法有误,静态方法不能访问非静态属性 
  13.      public static function getName2() 
  14.      { 
  15.          return self::$value
  16.      } 
  17.      public function getPI() 
  18.      { 
  19.        return self::PI;     
  20.      } 
  21.       
  22.       
  23.  } 

还要注意的一点是如果类的方法是static的,他所访问的属性也必须是static的.

在类的内部方法访问未声明为const及static的属性时,使用$this->value ='class_a';的形式.

波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 本站源码并不保证全部能正常使用,仅供有技术基础的人学习研究,请谨慎下载
8. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!

波比源码 » PHP中::、->、self、$this操作符

发表评论

Hi, 如果你对这款模板有疑问,可以跟我联系哦!

联系站长
赞助VIP 享更多特权,建议使用 QQ 登录
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡