php - 状态模式,return 无返回值的问题
黄舟
黄舟 2017-04-11 09:47:17
[PHP讨论组]

代码如下:
我使用echo是有值的,为啥我使用return就获取不到值呢?

class GoodNight implements IState  
{ 
    public function WriteCode(Work $w)  
    {  
        if($w->hour<22)  
        {  
           return Yii::t('yii','Good night'); 
        }else{  
            $w->SetState(new GoodAtNight());  
            $w->WriteCode();  
        }   
    }  
} 
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(2)
巴扎黑

谢谢邀请!因为你实例化掉用了本身,本身是return返回而不是输出之类的,所以不会出现值,这很正常!如果你直接echo掉用的就可以看到输出值了。

class GoodNight implements IState  
{ 
    public function WriteCode(Work $w)  
    {  
        if($w->hour<22)  
        {  
           return Yii::t('yii','Good night'); 
        }else{  
            $w->SetState(new GoodAtNight());  
            echo $w->WriteCode();  // 在这里echo就有值了
        }   
    }  
} 
PHPz

楼上回答错误 解决方法是递归调用错误 返回的时候没法进行跳出,解决方式:
class GoodNight implements IState
{

public function WriteCode(Work $w)  
{  
    if($w->hour<22)  
    {  
       return Yii::t('yii','Good night'); 
    }else{  
        $w->SetState(new GoodAtNight());  
        return $w->WriteCode();  
    }   
}  

}

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号