“内联" PHP中的类实例化? (为便于方法链接) [英] "Inline" Class Instantiation in PHP? (For Ease of Method Chaining)

查看:59
本文介绍了“内联" PHP中的类实例化? (为便于方法链接)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在OO语言(如Python和Ruby)中通常使用的一个惯用法是实例化对象和链接方法,这些方法返回对对象本身的引用,例如:

An idiom commonly used in OO languages like Python and Ruby is instantiating an object and chaining methods that return a reference to the object itself, such as:

s = User.new.login.get_db_data.get_session_data

在PHP中,可以像这样复制此行为:

In PHP, it is possible to replicate this behavior like so:

$u = new User();
$s = $u->login()->get_db_data()->get_session_data();

syntax error, unexpected T_OBJECT_OPERATOR中尝试以下结果:

$s = new User()->login()->get_db_data()->get_session_data();

这似乎可以使用静态方法来完成,这可能最终是我要做的,但是我想检查一下lazyweb:实际上有一种干净,简单的实例化PHP类的方法" "(如上面的片段所示)?

It seems like this could be accomplished using static methods, which is probably what I'll end up doing, but I wanted to check the lazyweb: Is there actually a clean, simple way to instantiate PHP classes "inline" (as shown in the above snippet) for this purpose?

如果我决定使用静态方法,让类的静态方法返回类本身的实例化是否太难了? (有效地编写我自己的构造函数,那不是一个构造函数吗?)感觉有点脏,但是如果没有太多可怕的副作用,我可能会做.

If I do decide to use static methods, is it too sorcerous to have a class's static method return an instantiation of the class itself? (Effectively writing my own constructor-that-isn't-a-constructor?) It feels kind of dirty, but if there aren't too many scary side effects, I might just do it.

我想我也可以使用get_user()方法来预先实例化UserFactory,但是我很好奇上述解决方案.

I guess I could also pre-instantiate a UserFactory with a get_user() method, but I'm curious about solutions to what I asked above.

推荐答案

所有这些提议的解决方案都会使您的代码复杂化,从而使PHP难以完成某些语法上的改进.希望PHP成为一种(不是很好的)东西,这是通往疯狂的道路.

All of these proposed solutions complicate your code in order to bend PHP to accomplish some syntactic nicety. Wanting PHP to be something it's not (like good) is the path to madness.

我只会用:

$u = new User();
$s = $u->login()->get_db_data()->get_session_data();

清晰,相对简洁,不涉及会引入错误的黑魔法.

It is clear, relatively concise and involves no black magic that can introduce errors.

当然,您总是可以使用Ruby或Python.它会改变你的生活.

And of course, you could always move to Ruby or Python. It will change your life.

  • 是的,我对PHP很苛刻.我每天都使用它.使用了多年.现实情况是,它已经积累了,而不是经过设计并显示出来.
  • And yeah, I am harsh on PHP. I use it every day. Been using it for years. The reality is that it has accreted, rather than been designed and it shows.

这篇关于“内联" PHP中的类实例化? (为便于方法链接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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