首页 > 解决方案 > 连续两次返回

问题描述

在查看某人的代码时,我在几个课程中连续遇到两个返回。例如:

class class1{
    private $property1;
    final function __construct($property1){    
        $this->property1 = $property1;
    }
    private $property2 = true;
    function method1($bool){
       $this->property2 = $bool;
       return $this;
       return new class1();
    }

它是如何工作的,这个结构是做什么用的?

标签: phpclass

解决方案


PHP 只允许一个返回语句。第一次返回之后的所有内容都将被忽略。在你的情况下,return new class1();永远不会被调用。

来自 PHP 文档:

如果从函数内部调用,return 语句会立即结束当前函数的执行,并将其参数作为函数调用的值返回。return 还结束 eval() 语句或脚本文件的执行。

您可以 在 php.net上查看更多信息


推荐阅读