PHP:防止链式方法返回?
对于一个返回值的相当简单的 PHP 类的方法链接,我有些头疼,有时需要经历解密过程:
$dataset = new Datacontainer;
$key = $dataset->get('key');
$key2 = $dataset->get('key')->decrypt();
get
方法是返回值所在的地方。因此,对第二行的 decrypt
方法的调用在当前状态下不起作用。
我可以做一些事情来设置 get
方法仅在没有任何链接时才返回,或者重构此代码的最佳方法是什么?
I am having some headaches regarding method chaining for a quite simple PHP class that returns a value, which sometimes need to go through a decryption process:
$dataset = new Datacontainer;
$key = $dataset->get('key');
$key2 = $dataset->get('key')->decrypt();
The get
method is where the return lives. So the call to the decrypt
method on the second row isn't going to work in its current state.
Can I do something to setup the get
method to return only when nothing is chained to it, or what would be the best way to re-factor this code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
get() 方法实际上并不知道是否有任何东西链接到它;但如果 get() 方法不返回任何内容(null),PHP 将抱怨尝试对非对象调用 decrypt() 方法。
您可以做的是将一个附加参数传递到 get() 方法中,指示它是否应该返回一个值,或者使用解密方法返回对象。
The get() method doesn't actually know whether anything is chained to it or not; but if the get() method returns nothing (null) PHP will complain about the attempt to call the decrypt() method on a non-object.
What you could do is pass an additional argument into the get() method that indicates whether it should return a value, or the object with the decrypt method.
不,那是不可能的。 (也许使用高度复杂的反射技术,但如果可能的话,这是不切实际的。)
我认为你们的班级结构有问题。通常,执行某些操作但返回工作实例的方法会更改类/实例的状态,例如通过属性,该属性又可以通过特殊/getter 方法获取。
No. That's not possible. (Maybe using highly complicated reflection-technology, but that's not practical, if possible at all.)
I think there is something wrong with the structure of your class. Usually a method that does something but returns the working-instance, changes the state of the class/instance, e.g. through an attribute, that again can be fetched through a special/getter method.
$dataset->get('key')
必须返回一个对象,其中decrypt()
是一个方法。目前尚不清楚您的decrypt()
方法属于哪个类。如果它是$dataset
类的一部分,那么您需要用两行调用它:$dataset->get('key')
has to return an object in whichdecrypt()
is a method. It isn't clear what class yourdecrypt()
method is a part of. If it's a part of your$dataset
class then you you need to call it in two lines:根据我目前对该过程的理解,我将采取以下方法:
解密数据的对象正在提供服务。 传入
此类对象通常作为协作者通过构造函数
:请注意,这里有改进的空间,从数据集中获取密钥(然后我需要更多地了解正在完成的工作,因此名称为 ClientClass) 。
Based on my current understanding of the process I would take the following approach:
An object that decrypts data is providing a service. Such objects are most often passed in
via the constructor as a collaborator:
Note that there is room for improvement here with the getting of the key from the dataset (then I would need to know more about what is being accomplished, hence the name ClientClass).