0

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;
}
3
  • There's no way for this. Only with phpdoc comments. Commented Aug 14, 2021 at 7:23
  • @u_mulder how does it relate to type-declaration? Commented Aug 14, 2021 at 7:28
  • What do you mean by "type array"? classA $someName denotes that that variable is of type classA, and not an array Commented Aug 14, 2021 at 15:29

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.