php self this parent区别,对比

来源:互联网 发布:2016全国各地上牌数据 编辑:程序博客网 时间:2024/06/14 10:55

1.this关键字

this是指向当前对象的指针,是在类被实例化之后才可以被使用。

this可以调用本类中的方法和属性,也可以调用父类中的可以调的方法和属性,可以说除过静态和const常量,基本上其他都可以使用this联络。


  1. class    test {  
  2.     public $public;  
  3.   
  4.     private $private;  
  5.   
  6.     protected $protected;  
  7.   
  8.     public function __construct(){  
  9.         $this->public = 'public-1';  
  10.         $this->private = 'private-1';  
  11.         $this->protected = 'protected-1';  
  12.     }  
  13.   
  14.     public function rank(){  
  15.         return $this->public;  
  16.     }  
  17.   
  18.     public function dell(){  
  19.         return $this->private;  
  20.     }  
  21.   
  22.     public function date(){  
  23.         return $this->protected;  
  24.     }  
  25. }  
  26.   
  27. $app = new test();  
  28. echo $app->rank();  
  29. echo "</br>";  
  30. echo $app->dell();  
  31. echo "</br>";  
  32. echo $app->date();  


2.self关键字

self是指向当前类的指针。对类本身,没有实例化的类。

self可以访问本类中的静态属性和静态方法,可以访问父类中的静态属性和静态方法。

用self时,不用实例化。

例子如下:

  1. class test {  
  2.   
  3.     static $instance;  
  4.   
  5.     public function __construct(){  
  6.         self::$instance = 'instance';//静态属性只能通过self来访问本类 
  7.     }  
  8.   
  9.     public function rank(){  
  10.         return self::$instance;//访问静态属性 $instance 
  11.     }  
  12. }  
  13.   
  14. $str = new test();  
  15. echo $str->tank();  

self 访问const定义的变量
  1. class test {  
  2.   
  3.     const  CITY= 'hangzhou';  
  4.   
  5.     public function rank(){  
  6.         return self::CITY;  
  7.     }  
  8. }  
  9.   
  10. $str = new test();  
  11. echo $str->rank();  


3.parent

PHP5中使用parent::来引用父类的方法。

parent:: 可用于调用父类中定义的成员方法。

parent::的追溯不仅于直接父类。

parent是指向父类的指针,一般我们使用parent来调用父类的构造函数

一个例子程序:

<?php
 //建立基类fruit
 class Fruit
 {
    public $name; //基类的属性,名字$name

    //基类的构造函数,初始化赋值
    public function __construct( $name )
    {
         $this->name = $name;
    }
 }

 //定义派生类apple继承自fruit类
 class Apple extends Fruit
 {
    public $breed;       //对于派生类,新定义了属性$breed品种、$area产地
    public $area;

    //派生类的构造函数
    function __construct( $breed, $area)
    {
         parent::__construct( "appleapple");    //使用parent调用了父类的构造函数 语句①
         $this->bread= $bread;
         $this->area = $area;
    }

    //派生类的成员函数,
    function detail()
    {
         print( $this->name. " is ".$this->bread. ",area is ".$this->area );
     }
 }

 //实例化Person对象
 $personObject = new Apple( "fushi", "hangzhou");

 //执行打印
 $personObject->detail();//输出结果:

 ?>

成员属性都是public(公有属性和方法,类内部和外部的代码均可访问)的,特别是父类的,这是为了供继承类通过this来访问。关键点在语句①:parent::__construct( "heiyeluren"),这时候我们就使用parent来调用父类的构造函数进行对父类的初始化,这样,继承类的对象就都给赋值了name为appleapple




0 0
原创粉丝点击