0

I am trying to design a class which containes an array of another class objects


<?php 

class X { };

class Y {
  private ?X[] items;
}

But this apparently doesn't work ..

I dont want to declare items as array because I need it to be in X type .

3
  • 1
    This is not currently possible directly in PHP. You need to either create a dedicated subclass or just rely on type-hinting in PHP docblocks Commented Jun 22, 2022 at 12:02
  • No there's no such a thing in PHP. And you don't need it in this case, since your items is marked private and you can declare type in your setter method signature as function addItem( \X $item ){...}; Commented Jun 22, 2022 at 13:36
  • For further reference in case you are anyone else is interested, there was a specific RFC dedicated to this, a generic array RFC, and a full-blown generic RFC, all of which were declined or didn't make it into vote. There's links to the discussions if you want to learn about the reasons. Commented Jun 22, 2022 at 13:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.