php const l类内使用,php类中的$this,static,const,self这几个关键字使用方法

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

$this

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

/**

* 有关人类

*/

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

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

/**

* 示例

*/

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

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

* 示例*/

classPerson

{const PI=1;static functiongetPi(){return self::PI;

}static functionprintPi(){echo self::getPi();

}

}

Person::printPi();?>

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

self

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

原文:http://www.cnblogs.com/freelyflying/p/7008072.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值