Search code examples
phpstaticstatic-methodsstatic-classes

Should data that is the same across all class instantiations be held in a separate, static class?


If I have a class that will be instantiated that needs to reference data and/or functions that will be the same for each class. How should this be handled to follow proper programming practices

Example (in PHP):

class Column {
    $_type = null;
    $_validTypes = /* Large array of type choices */;

    public function __construct( $type ) {
        if( type_is_valid( $type ) ) {
             $_type = $type;
        }
    }

    public function type_is_valid( $type ) {
        return in_array( $type, $_validTypes );
    }
}

Then every time a Column is created, it will hold the $_validTypes variable. This variable only really needs to be defined once in memory where all Columns created could refer to a static function type_is_valid for a static class which would hold the $_validTypes variable, declared only once.

Is the idea of a static class, say ColumnHelper or ColumnHandler a good way to handle this? Or is there a way to hold static data and methods within this class? Or is this redefining of $_validTypes for each Column an okay way to do things?


Solution

  • One option would be create a new model for the column configuration e.g.

    class ColumnConfig {
        private $validTypes;
        public isValid($type){
            return isset($this->validType($type))?true:false;
        }
    }
    

    then either add it once to API if you have one, or create one global instance e.g.

    $cc = new ColumnConfig();
    class Column {
        private $cc;
        function __construct($type){
            $this->cc = $this->api->getCC(); // if you have api
            global $cc; // assuming you have no api, an you create a global $cc instance once.
            $this->cc = $cc; // <-- this would pass only reference to $cc not a copy of $cc itself.
    
            if ($this->cc->isValid($type)){
              ....
            }
        }
    }
    

    Sounds like way to go.