2

I wrote a class to set and expire browser cookies. I'm trying to set the classes public variables to the value of a global variable in a way that would allow me to use the classes methods statically. Basically all I want to do is remove the duplicate global $settings, and the $expire and $domain variables.

Here's my code as it sits:

<?php

    class cookies {
        public static function set($name, $value, $date = false) {
            global $settings;

            $expire = ($date) ? $date : $settings['expire'];
            $domain = str_replace('www.', '', $settings['domain']);
            setcookie($name, $value, $expire, '/', $domain);
        }

        public static function clear() {
            global $settings;

            $domain = str_replace('www.', '', $settings['domain']);
            setcookie('test1', '', 1, '/', $domain);
            setcookie('test2', '', 1, '/', $domain);
        }
    }

?>
Coffee'd Up Hacker
  • 1,356
  • 11
  • 23

1 Answers1

7

Using global variables is very bad for the flexibility, modularity and sanity of your app. Using static method is very bad for the modularity and flexibility of your app. Using both together is an abomination. How about you write a class that can be used like this:

$cookies = new Cookies($settings['expire'], $settings['domain']);
$cookies->set(.., .., ..);
$cookies->clear();

You'd start with a proper class structure like this:

class Cookies {

    protected $expire,
              $domain;

    public function __construct($expire, $domain) {
        $this->expire = $expire;
        $this->domain = $domain;
    }

    ...

}

Then you use $this->expire and $this->domain instead of global variables.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889