Does PHP have an answer to Java style class generics?

前端 未结 8 1509
天命终不由人
天命终不由人 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 02:00

    One alternative is the combination of splat operator + typed hint + private array:

    name = $name;
        }
        
    }
    
    class Classe {
        
        private $students = [];
        
        public function add(Student ...$student){
            array_merge($this->students, $student);
        }
        
        public function getAll(){
            return $this->students;
        }
        
    }
    
    $c = new Classe();
    $c->add(new Student('John'), new Student('Mary'), new Student('Kate'));
    

提交回复
热议问题