方法链 PHP OOP

Method Chains PHP OOP(方法链 PHP OOP)
本文介绍了方法链 PHP OOP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

通常,在许多框架中,您可以找到使用查询构建器创建查询的示例.你经常会看到:

Commonly, in a lot of frameworks, you can find examples of creating a query using the query builder. Often you will see:

$query->select('field');
$query->from('entity');

但是,在某些框架中你也可以这样做

However, in some frameworks you can also do it like this

$object->select('field')
       ->from('table')   
       ->where( new Object_Evaluate('x') )
       ->limit(1) 
       ->order('x', 'ASC');

您实际上是如何制作这种链条的?

How do you actually do this kinds of chains?

推荐答案

这叫做 Fluent Interface -- 该页面上有一个 PHP 示例.

This is called Fluent Interface -- there is an example in PHP on that page.

基本思想是该类的每个方法(您希望能够链接) 必须返回 $this -- 这使得调用其他方法成为可能返回的 $this 上同一个类的方法.

The basic idea is that each method (that you want to be able to chain) of the class has to return $this -- which makes possible to call other methods of that same class on the returned $this.

当然,每个方法都可以访问类的当前实例的属性——这意味着每个方法都可以向当前实例添加一些信息".

And, of course, each method has access to the properties of the current instance of the class -- which means each method can "add some information" to the current instance.

这篇关于方法链 PHP OOP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)