博主信息
博文 38
粉丝 0
评论 3
访问量 51039
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
new static的细说
意外的博客
原创
3818人浏览过

1.new static()是在PHP5.3版本中引入的新特性。

2.无论是new static()还是new self(),都是new了一个新的对象。

3.这两个方法new出来的对象有什么区别呢,说白了就是new出来的到底是同一个类实例还是不同的类实例呢?

为了探究上面的问题,我们先上一段简单的代码:

复制代码

class Father {

    public function getNewself() {

        return new self();

    }

    public function getNewstatic() {

        return new static();

    }

}

$f = new Father();


print get_class($f->getNewself());

print get_class($f->getNewstatic());

复制代码

注意,上面的代码get_class()方法是用于获取实例所属的类名。

这里的结果是:无论调用getNewself()还是调用getNewstatic()返回的都是Father这个类的实例。

打印的结果为:Father Father

到这里,貌似new self()和new static()是没有区别的。我们接着往下走:

复制代码

class Sun1 extends Father {

}

class Sun2 extends Father {

}

$sun1 = new Sun1();

$sun2 = new Sun2();


print get_class($sun1->getNewself()); //Father

print get_class($sun1->getNewstatic()); //Sun1

print get_class($sun2->getNewself()); //Father

print get_class($sun2->getNewstatic()); //Sun2


复制代码

看上面的代码,现在这个Father类有两个子类,由于Father类的getNewself()和getNewstatic()是public的,所以子类继承了这两个方法。

打印的结果是:FatherSun1FatherSun2

我们发现,无论是Sun1还是Sun2,调用getNewself()返回的对象都是类Father的实例,而getNewstatic()则返回的是调用者的实例。

即$sun1返回的是Sun1这个类的实例,$sun2返回的是Sun2这个类的实例。

 

new self()和new static()的区别了。

首先,他们的区别只有在继承中才能体现出来,如果没有任何继承,那么这两者是没有区别的。

然后,new self()返回的实例是万年不变的,无论谁去调用,都返回同一个类的实例,

**而new static()则是由调用者决定的。

上面的$sun1->getNewstatic()的调用者是$sun1对吧!$sun1是类Sun1的实例.

所以返回的是Sun1这个类的实例,$sun2同样的道理就不赘述了。

例子:

class test{

    protected static $instance = null;

    public static function getInstance(){

        if (is_null(static::$instance)) {

            static::$instance = new static;

        }

    return static::$instance;

    }

}

**谁调用,new static()指向的是谁,那么,这里new static()指向的就是$instance ;因为上一行判断代码调用了$instance ;




本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学