2

Given I have the following method:

public function create(array $notificationTypes, NotificationSettings $notificationSettings)
{

}

Is it in any way possible to make sure the $notificationTypes parameter is an array of NotificationType? I tried the following, but it doesn't work:

 public function create(array NotificationType $notificationTypes, NotificationSettings $notificationSettings)
 {

 }

 public function create(NotificationType[] $notificationTypes, NotificationSettings $notificationSettings)
 {

 }

If this isn't possible, is there no other way than looping through $notificationTypes and check if each element is an instance of NotificationType?

Thanks for reading!

6
  • 3
    php.net/manual/en/language.operators.type.php ? Commented Jun 13, 2016 at 10:51
  • 2
    No, you only can check if passed argument is array and inside a function check every element of this array. Commented Jun 13, 2016 at 10:53
  • You have to manually iterate over all the elements of your array, PHP does not support that kind of type-hinting. Commented Jun 13, 2016 at 10:53
  • Alright, if you can answer the question, I will accept it. Thank you. Commented Jun 13, 2016 at 10:54
  • 4
    The language does not support it natively. You can emulate it with regular objects (I've seen a few typed collection implementations out there) but it needs some extra work. Commented Jun 13, 2016 at 11:02

2 Answers 2

2

As the comments said, you cannot do that in the method declaration. In a reasonably recent PHP version you can check the array items' types like this in the function body:

if (count(array_filter($notificationTypes,
              function($inst) {
                  return ! ($inst instanceof NotificationType));
              }))) {
    throw new Exception('Only instances of NotificationType please!');
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you don't want to check types manually you can use expectsAll function from NSPL. There are also other functions and predefined constraints for argument validation.

use function \nspl\args\expectsAll;

//...

public function create(array $notificationTypes, NotificationSettings $notificationSettings)
{
    expectsAll(NotificationType::class, $notificationTypes);
}

// ...

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.