Does PHP have an answer to Java style class generics?

前端 未结 8 1497
天命终不由人
天命终不由人 2020-12-24 01:09

Upon building an MVC framework in PHP I ran into a problem which could be solved easily using Java style generics. An abstract Controller class might look something like thi

8条回答
  •  無奈伤痛
    2020-12-24 01:59

    My workaround is the following:

    /**
     * Generic list logic and an abstract type validator method.
     */    
    abstract class AbstractList {
        protected $elements;
    
        public function __construct() {
            $this->elements = array();
        }
    
        public function add($element) {
            $this->validateType($element);
            $this->elements[] = $element;
        }
    
        public function get($index) {
            if ($index >= sizeof($this->elements)) {
                throw new OutOfBoundsException();
            }
            return $this->elements[$index];
        }
    
        public function size() {
            return sizeof($this->elements);
        }
    
        public function remove($element) {
            validateType($element);
            for ($i = 0; $i < sizeof($this->elements); $i++) {
                if ($this->elements[$i] == $element) {
                   unset($this->elements[$i]);
                }
            }
        }
    
        protected abstract function validateType($element);
    }
    
    
    /**
     * Extends the abstract list with the type-specific validation
     */
    class MyTypeList extends AbstractList {
        protected function validateType($element) {
            if (!($element instanceof MyType)) {
                throw new InvalidArgumentException("Parameter must be MyType instance");
            }
        }
    }
    
    /**
     * Just an example class as a subject to validation.
     */
    class MyType {
        // blahblahblah
    }
    
    
    function proofOfConcept(AbstractList $lst) {
        $lst->add(new MyType());
        $lst->add("wrong type"); // Should throw IAE
    }
    
    proofOfConcept(new MyTypeList());
    

    Though this still differs from Java generics, it pretty much minimalizes the extra code needed for mimicking the behaviour.

    Also, it is a bit more code than some examples given by others, but - at least to me - it seems to be more clean (and more simliar to the Java counterpart) than most of them.

    I hope some of you will find it useful.

    Any improvements over this design are welcome!

提交回复
热议问题