douxin2002 2012-03-28 18:56
浏览 13
已采纳

具有不同返回值的函数链接?

Is it possible to have a method return different values depending on context (how the return value is used)? For example, could a method return $this when it's then used with the arrow operator to call another method (i.e. chaining method calls), but return a scalar when the return value isn't used this way?

Case 1:

$result = $test->doSomething1(); // returns 4
// $result returns 4

Case 2:

$result = $test->doSomething1()->doSomething2();
// doSomething1() returns $this
// doSomething2() returns 8

Is there anyway to perform such a behaviour?

  • 写回答

3条回答 默认 最新

  • dongzai3917 2012-03-28 19:12
    关注

    If I understand the question correctly, you want a method (doSomething1) to return a value based on what the rest of the call chain looks like. Unfortunately, there is absolutely no way you can do this.

    Common programming paradigms shared across "all" languages (how methods, operators and such work in the context of the grammar) dictate that the result of the expression $this->doSomething1() has to be worked out before the result of possibly calling ->doSomething2() on it can be considered. Statically typed and dynamically typed languages do this in different ways, but the common factor is that the expression $this->doSomething1() has to be considered independently of what follows or does not follow.

    In a nutshell: $this->doSomething1() has to return a specific type of value in both cases. And in PHP there is no way to have a type of value that can behave like a number in one context and like an object with methods to call in another.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度