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

将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条)

报告相同问题?

悬赏问题

  • ¥15 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?