dpa84373 2018-04-15 06:36
浏览 99
已采纳

将void方法的返回值赋给变量有什么意义? [关闭]

class test {
    public function hello() {
        echo "hello!";
    }
    public function assign() {
        $var = $this->hello();
        $this->hello(); //both seem to be doing the same thing
    }
}

This is a simplified example of a piece of code that I am talking about, which is here on line 43: https://eval.in/988393

What is the point of a assigning a method call (I guess this is how it is called) to a variable and what is the explanation of this causing it to get run (it does not just assign it but it executes the code).

PS: This is actually related to Iterators like here: http://php.net/manual/en/class.iterator.php . Somebody told me this:

"The point with iterators is that you do not care how the methods are called, you only care about each single method separatly".

What did this person mean?

  • 写回答

2条回答 默认 最新

  • dongyong6045 2018-04-15 08:05
    关注

    Basically, in your example and the linked example of the iterator, assigning the return value is unnecessary.

    • In your example it is because there is no return value. In other words, the function returns void which will cause $var to be null. In general, if a function contains no return statement at all or only a return; (note that there is no variable being returned), it is useless to store the result in a variable.
    • In the iterator example it is unnecessary, because the value isn't used. But the $current variable does still contain the actual value of the current iteration - it is not null (except when the array contains null, obviously). Actually calling $this->current() wouldn't be necessary at all in the iterator implementation - it looks like it is done solely for the purpose of getting the nice output of echo "current: $var "; when checking for the validity.

    There have been other questions asked about void return types in the past as well, e.g. Void as return type.


    By the way, if your question was also about storing a function in a variable (and not its result), then you probably meant something like this:

    function foo() {
        echo 'bar';
    }
    
    $var = 'foo';
    $var(); // outputs: bar
    

    But be careful with these kinds of function invokations, there are quite some pitfalls coming with them.

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

报告相同问题?

悬赏问题

  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”