问题描述
我正在观看 PHP 视频讲座.我的项目目录中有 user
类现在在教程中的静态函数中,它像这样实例化
I was watching PHP video lectures . I have user
class in my project directory now in tutorial inside a static function its instantiated like this
private static function instantiate($result){
$object = new self;
//here goes loop
}
在某处像这样使用
$object= new user();
有人请指导我关于第一种情况的概念,它说 new self
Will someone please guide me about the concept of first case where it says new self
推荐答案
"self" 是引用当前类的关键字.它仅在类的代码中可用.
"self" is a keyword that references the current class. It is only available inside the class' code.
您可以使用它来调用您自己的类上的方法,但由于绑定,您也可以使用它来调用超类上的方法.
You can use it to call methods on your own class, but due to binding you can also use it to call methods on a superclass.
考虑以下示例:
class TestA {
public static function makeNewInstance() {
return new TestA();
}
}
class TestB extends TestA {
}
现在,调用 TestB::makeNewInstance();将返回一个 TestA 实例.(TestB 继承了该方法,但它直接链接到 TestA,因此仍会返回该方法)
Now, calling TestB::makeNewInstance(); will return an instance of TestA. (TestB inherits the method, but it's linked directly to TestA so will still return that)
与这个比较:
class TestA {
public static function makeNewInstance() {
return new self();
}
}
class TestB extends TestA {
}
现在,调用 TestB::makeNewInstance() 将返回 TestB 的一个实例.(由于 self 引用了活动类,并且您在 TestB 上调用它,因此self"的内容现在是 TestB 而不是 TestA.
Now, calling TestB::makeNewInstance() will return an instance of TestB. (Since self references the active class, and you're calling it on TestB, the contents of "self" is now TestB instead of TestA.
希望能为您解释.否则,也许您问题中的更多细节将有助于吸引更具体的答案.
Hope that explains for you. Otherwise, maybe some more detail in your question would help attract more specific answers.
这篇关于PHP:区别黑白新自我和新对象()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!