dougan1884 2014-04-25 11:27
浏览 17
已采纳

适合使这个类静态吗?

I've got a small input helper class.

I read a lot that static classes are not the best to use. But I still haven't grasp why I shouldn't use static classes. I'm not that advanced yet, so maybe I will figure it out later on.

The reason I made it static is that it's not an object that's unique every time it's being called in my script.

Is it a good thing that I made the class static?

class Input {
    public static function exists($type = 'post') {
        switch($type) {
            case 'post':
                return (!empty($_POST)) ? true : false;
            break;
            case 'get':
                return (!empty($_GET)) ? true : false;
            break;
            default:
                return false;
            break;
        }
    }

    public static function get($input, $source = 'post') {
        if($source == 'post' && isset($_POST[$input])) {
            return $_POST[$input];
        } else if($source == 'get' && isset($_GET[$input])) {
            return $_GET[$input];
        }
        return false;
    }
}

EDIT: Updated code

class Input {
    private $_get,
            $_post;

    public function __construct($get, $post) {
        $this->_get  = $get;
        $this->_post = $post;
    }

    public function exists($type = 'POST') {
        switch($type) {
            case 'POST':
                return (!empty($this->_post)) ? true : false;
            break;
            case 'GET':
                return (!empty($this->_get)) ? true : false;
            break;
            default:
                return false;
            break;
        }
    }

    public function get($input, $source = 'POST') {
        if($source == 'POST' && isset($this->_post[$input])) {
            return $this->_post[$input];
        } elseif($source == 'GET' && isset($this->_get[$input])) {
            return $this->_get[$input];
        }
        throw new Exception('Undefined index: ' . $input);
    }
}
  • 写回答

2条回答 默认 最新

  • dongzhang5006 2014-04-25 11:31
    关注

    Just because you have only one of something doesn't mean it has to be static. Especially in regard to Unit tests, static classes are hard to deal with.

    Your class Input is bound to $_GET and $_POST. This means you can not use it in Unit tests.

    If instead your class looked like this:

    $input = new Input($_GET, $_POST);
    

    ie. you give it the global dependencies, now Input can be tested because you can mock the values of $_GET and $_POST.

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

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真