PHP中new self()和new static()的区别
1.new static()是在PHP5.3版本中引入的新特性。
2.无论是new static()还是new self(),都是new了一个新的对象。
3.这两个方法new出来的对象有什么区别呢,说白了就是new出来的到底是同一个类实例还是不同的类实例呢?
为了探究上面的问题,我们先上一段简单的代码:
class Father {
public function getNewFather() {
return new self();
}
public function getNewCaller() {
return new static();
}
}
$f = new Father();
print get_class($f->getNewFather());
print get_class($f->getNewCaller());
注意,上面的代码get_class()方法是用于获取实例所属的类名。
这里的结果是:无论调用getNewFather()还是调用getNewCaller()返回的都是Father这个类的实例。
打印的结果为:FatherFather
到这里,貌似new self()和new static()是没有区别的。我们接着往下走:
class Sun1 extends Father {
}
class Sun2 extends Father {
}
$sun1 = new Sun1();
$sun2 = new Sun2();
print get_class($sun1->getNewFather());
print get_class($sun1->getNewCaller());
print get_class($sun2->getNewFather());
print get_class($sun2->getNewCaller());
看上面的代码,现在这个Father类有两个子类,由于Father类的getNewFather()和getNewCaller()是public的,所以子类继承了这两个方法。
打印的结果是:$sun1->getNewFather() 为: Father
$sun1->getNewCaller() 为:Sun1
$sun2->getNewFather() 为: Father
$sun2->getNewCaller() 为:Sun2
我们发现,无论是Sun1还是Sun2,调用getNewFather()返回的对象都是类Father的实例,而getNewCaller()则返回的是调用者的实例。
即$sun1返回的是Sun1这个类的实例,$sun2返回的是Sun2这个类的实例。
现在好像有点明白new self()和new static()的区别了。
首先,他们的区别只有在继承中才能体现出来,如果没有任何继承,那么这两者是没有区别的。
然后,new self()返回的实例是万年不变的,无论谁去调用,都返回同一个类的实例,而new static()则是由调用者决定的。
上面的$sun1->getNewCaller()的调用者是$sun1对吧!$sun1是类Sun1的实例,所以返回的是Sun1这个类的实例,$sun2同样的道理就不赘述了。
本文源自:https://www.cnblogs.com/shizqiang/p/6277091.html ,谢谢博友的讲解。
相关文章
- 使用PHP + Apache访问有错误的php脚本时不报错
- php中的include和require的区别
- PHP ~ 通过程序删除图片,同时删除数据库中的图片数据 和 图片文件
- 区别 PHP 的 $_POST、$HTTP_RAW_POST_DATA 和 php://input
- PHP生成GUID的函数
- PHP中exit()与die()的区别
- PHP判断变量是否存在及函数isset() 、empty()与is_null的区别
- 获取PHP文件绝对地址$_SERVER['SCRIPT_FILENAME'] 与 __FILE__ 的区别
- PHP5.3配置文件php.ini-development和php.ini-production的区别
- Windows下图文详解PHP三种运行方式(php_mod、cgi、fastcgi)
- 利用PHP的register_shutdown_function来记录PHP的输出日志,模拟析构函数
- 【荐】怎么用PHP发送HTTP请求(POST请求、GET请求)?
- PHP Socket编程 之 php实现http服务
- 分享b站PHP学习视频整理
- PHP 面试踩过的坑
- 修改范围PHP_INI_SYSTEM与PHP_INI_ALL的区别
- 不折腾之搭建Mac上的PHP开发环境[转]
- PHP不影响正常运行的调试技巧
- [PHP] 常备的现代 PHP 项目开发准备
- [php-src] 窥探Php内核中的数组与面向对象
- Atitit. 委托的本质 c#.net java php的比较
- atitit.压缩算法 ZLib ,gzip ,zip 最佳实践 java .net php
- php 多维数组排序
- mac apache php mysql nginx php接口的简单demo