php – 使用抽象类返回新的$this
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 使用抽象类返回新的$this,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1449字,纯文字阅读大概需要3分钟。
内容图文
![php – 使用抽象类返回新的$this](/upload/InfoBanner/zyjiaocheng/728/166ada679e1441e5bf2d86c245d57072.jpg)
我发现我的代码有些麻烦,并且不明白它为什么会这样做.有人能解释一下吗?
我们有:
abstract class AbstractThing
{
public function search(...)
{
$ret = false;
$data = $database->query(...);
foreach($data as $values)
{
$item = new $this;
$item->fill_with_values($values);
$ret []= $item;
}
return $ret;
}
}
它可以按预期工作,并在成功搜索时返回对象实例:
class Thing extends AbstractThing
{
// ...
}
$thing = new Thing;
$things = $thing->search(...); // Thing[] on success, false on failure
但是,如果我希望稍微缩短代码,它会破坏:
abstract class AbstractThing
{
public function search(...)
{
$ret = false;
$data = $database->query(...);
foreach($data as $values) {
$ret []= (new $this)->fill_with_values($values);
}
return $ret;
}
}
这返回布尔值为true.为什么?它适用于不是从抽象类继承的类.
解决方法:
当我们分配时:
$ret []= (new $this)->fill_with_values($values);
…我们没有设置$ret [] =(new $this).相反,此语句将fill_with_values()的返回值推送到数组中,因为它最后执行.
看起来你正试图实现类似于factory method pattern的东西.考虑一下:
abstract class AbstractThing
{
...
public static function fill($values)
{
$instance = new static;
$instance->fill_with_values($values);
return $instance;
}
}
然后我们可以在你的问题中实际完成你想要完成的事情:
$ret[] = static::fill($values);
这是有效的,因为fill()的返回值是类的实例,而不是fill_with_values()的返回值.此上下文中的static关键字使用后期静态绑定来解析执行代码的类的类型(在本例中为Thing)而不是声明它的类,因此它通过继承来工作.有关更多信息,请参见this question.
内容总结
以上是互联网集市为您收集整理的php – 使用抽象类返回新的$this全部内容,希望文章能够帮你解决php – 使用抽象类返回新的$this所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。