php self()与当前对象的构造函数 [英] php self() with current object's constructor
本文介绍了php self()与当前对象的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使new self()
使用当前实例的构造函数的正确方法是什么?换句话说,当我这样做时:
What's the proper way to get new self()
to use the current instance's constructor? In other words, when I do:
class Foo{
function create(){
return new self();
}
}
Class Bar extends Foo{
}
$b = new Bar();
echo get_class($b->create());
我想查看:Bar
而不是:Foo
推荐答案
public static function create()
{
$class = get_called_class();
return new $class();
}
这应该有效.
class Foo{
public static function create()
{
$class = get_called_class();
return new $class();
}
}
class Bar extends Foo{
}
$a = Foo::create();
$b = Bar::create();
echo get_class($a), PHP_EOL, get_class($b);
显示:
Foo Bar
UPD:
如果要使用非静电,则:
If you want non-statics, then:
<?php
class Foo{
public function create()
{
$class = get_class($this);
return new $class();
}
}
class Bar extends Foo{}
$a = new Bar();
$b = $a->create();
echo get_class($a), PHP_EOL, get_class($b);
?>
显示:
Bar Bar
这篇关于php self()与当前对象的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文