dongtuwu8548 2017-09-02 00:43
浏览 15
已采纳

在另一个方法中调用方法是一个好习惯吗? - PHP

I would like to know if it's recommended to do this:

class User {

    public function __construct() {
        parent::__construct();
    }
    public function exists($token) {
        //return true if token exists otherwise return false
    }
    public function createSession($token) {
        if($this->exists($token))
            //create session
        else
            //redirect
    }
}

I think it could be not recommended in case of a change in the exists method of the class but I think that'll not happen, What do you recommend me to do?

  • 写回答

2条回答 默认 最新

  • dozr162106 2017-09-02 00:52
    关注

    There's nothing wrong with calling methods from other methods. In many designs, it's critical that you do this. This allows you to create subclasses that redefine the method, and the new definition will be called.

    So if you do:

    class SpecialUser extends User {
        public function exists($token) {
            // determine token existence in some other way
        }
    }
    

    You can then do:

    $s = new SpecialUser;
    $s->createSession($someToken);
    

    and it will make use of the special way that SpecialUser checks tokens.

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

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)