new self() 是做什么的;在 PHP 中是什么意思? [英] What does new self(); mean in PHP?

查看:37
本文介绍了new self() 是做什么的;在 PHP 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从未见过这样的代码:

I've never seen code like this:

public static function getInstance()
{
    if ( ! isset(self::$_instance)) {
        self::$_instance = new self();
    }
    return self::$_instance;
}

new className()一样吗?

编辑

如果类是继承的,它指向哪个类?

If the class is inheritant,which class does it point to?

推荐答案

self 指向编写它的类.

因此,如果您的 getInstance 方法在类名 MyClass 中,则以下行:

So, if your getInstance method is in a class name MyClass, the following line :

self::$_instance = new self();

会做同样的事情:

self::$_instance = new MyClass();



评论后的更多信息.

如果你有两个相互扩展的类,你有两种情况:

If you have two classes that extend each other, you have two situations :

  • getInstance 在子类中定义
  • getInstance 在父类中定义
  • getInstance is defined in the child class
  • getInstance is defined in the parent class

第一种情况看起来像这样(对于这个例子,我已经删除了所有不必要的代码——你必须重新添加它以获得单例行为)* :

The first situation would look like this (I've removed all non-necessary code, for this example -- you'll have to add it back to get the singleton behavior)* :

class MyParentClass {
    
}
class MyChildClass extends MyParentClass {
    public static function getInstance() {
        return new self();
    }
}

$a = MyChildClass::getInstance();
var_dump($a);

在这里,你会得到:

object(MyChildClass)#1 (0) { } 

这意味着 self 意味着 MyChildClass -- 即编写它的类.

Which means self means MyChildClass -- i.e. the class in which it is written.

class MyParentClass {
    public static function getInstance() {
        return new self();
    }
}
class MyChildClass extends MyParentClass {
    
}

$a = MyChildClass::getInstance();
var_dump($a);

你会得到这样的输出:

object(MyParentClass)#1 (0) { }

这意味着 self 意味着 MyParentClass -- 即这里也是,编写它的类.

Which means self means MyParentClass -- i.e. here too, the class in which it is written.

class MyParentClass {
    public static function getInstance() {
        return new static();
    }
}
class MyChildClass extends MyParentClass {
    
}

$a = MyChildClass::getInstance();
var_dump($a);

但是,使用 static 而不是 self,你现在会得到:

But, with static instead of self, you'll now get :

object(MyChildClass)#1 (0) { } 

这意味着 static 指向使用的类(我们使用了 MyChildClass::getInstance()),而不是写在其中的那个.

Which means that static sort of points to the class that is used (we used MyChildClass::getInstance()), and not the one in which it is written.

当然,self 的行为并没有改变,为了不破坏现有的应用程序——PHP 5.3 只是增加了一个新的行为,回收了 static 关键字.

Of course, the behavior of self has not been changed, to not break existing applications -- PHP 5.3 just added a new behavior, recycling the static keyword.

这篇关于new self() 是做什么的;在 PHP 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆