phpstrong-typingtype-declaration

How to create a `Typed` array in php?


I'd like to do something like that, creating a defined type array of classA inside classB, However, I can't find the syntax.

class classA{
}
class classB{
    private classA $someName:array;
}

Solution

  • there are no typed arrays in php, but you may implement a wrapping class to an array, or a set of functions with variadic arguments. for instance:

    class classB{
        private array $arr;
        public function __construct(classA ...$classAs){
           this->$arr = $classAs;
        }
    }
    

    you may read more about it here: https://www.cloudsavvyit.com/10040/approaches-to-creating-typed-arrays-in-php/

    another approach could be to extend the array class, and make a typecheck with instanceof on each element as mentioned here: Type hinting - specify an array of objects