self static this parent 关键词的基本用法
2018-01-16 16:36
447 查看
在使用面向对象的时候,总会被几个词迷惑,self 自己,this 这个 ,static 静态的,parent 父亲,到底这些是什么鬼,大家跟着我的实例走,就能洞悉其中的微妙了
self 被用作当前类的一个引用
输出:
a :hello world
a :hello world
static 后期静态绑定 static::不再被解析为定义当前方法所在的类,而是在实际运行时计算的 如下面的例子,注意他的输出
输出:
a :hello world
ab :hello world
$this 当前类的一个实例
parent 指定当前类的父类
输出:
a :hello world
实例测试:
输出:
A
C
C
总结:这是这些关键字进行方法调用的时候,主要明确该调用哪个类的方法。php 的static 是专门用来做延期静态绑定的,其他的关键字,在加载的时候其实已经明确了。大家如有疑问,欢迎留言咨询
self 被用作当前类的一个引用
<?php class a { public static function hello() { self::showHello(); } public static function showHello() { echo __CLASS__ . " :hello world <br />"; } } a::hello(); class ab extends a { public static function showHello() { echo __CLASS__ . " :hello world<br />"; } } ab::hello();
输出:
a :hello world
a :hello world
static 后期静态绑定 static::不再被解析为定义当前方法所在的类,而是在实际运行时计算的 如下面的例子,注意他的输出
<?php class a { public static function hello() { static::showHello(); } public static function showHello() { echo __CLASS__." :hello world <br />"; } } a::hello(); class ab extends a { public static function showHello() { echo __CLASS__." :hello world<br />"; } } ab::hello();
输出:
a :hello world
ab :hello world
$this 当前类的一个实例
<?php class a { public function hello() { $this->showHello(); } public function showHello() { echo __CLASS__." :hello world <br />"; } } $a=new a(); $a->hello(); class ab extends a { public function showHello() { echo __CLASS__." :hello world<br />"; } } $ab=new ab(); $ab->hello();
parent 指定当前类的父类
<?php class a { public function hello() { $this->showHello(); } public function showHello() { echo __CLASS__ . " :hello world <br />"; } } class ab extends a { public function hello() { parent::showHello(); } public function showHello() { echo __CLASS__ . " :hello world<br />"; } } $ab = new ab(); $ab->hello();
输出:
a :hello world
实例测试:
<?php class A { public static function foo() { static::who(); } public static function who() { echo __CLASS__."\n"; } } class B extends A { public static function test() { A::foo(); parent::foo(); self::foo(); } public static function who() { echo __CLASS__."\n"; } } class C extends B { public static function who() { echo __CLASS__."\n"; } } C::test();
输出:
A
C
C
总结:这是这些关键字进行方法调用的时候,主要明确该调用哪个类的方法。php 的static 是专门用来做延期静态绑定的,其他的关键字,在加载的时候其实已经明确了。大家如有疑问,欢迎留言咨询
相关文章推荐
- parent:: self:: static $this->php
- php中this,self,parent三个关键字用法
- static,this,self,parent
- java中this,static关键词的用法
- php中$this、static、final、const、self 等几个关键字的用法
- 举例说明 this,self,parent 的区别用法
- php中$this、static、final、const、self 等几个关键字的用法
- self,parent,this的区别和用法
- php杂谈【基础篇】之_11.理解PHP中this,self,parent三个关键字用法
- PHP 中 this,self,parent 的区别、用法
- PHP5 面向对象程序设计之:this, self, parent, static和const
- PHP 之 this self parent static 对比
- PHP中this,self,parent的区别之一this篇
- Java中static、this、super、final用法简谈(一)
- PHP中this,self,parent的区别
- PHP中this,self,parent的区别
- PHP中this,self,parent 三个关键字之间的区别
- Java中static、this、super、final用法
- php class中self,parent,this的区别,以及实例
- Java中static、this、super、final的用法