0

I laravel 9 I have installed "bensampo/laravel-enum": "^5.2" and created new enum with command php artisan make:enum SearchDataType

and I wonder if there is a way to describe function with array of SearchDataType elements, like :

public function searchSiteContent(string $s = '', bool $partial= false, SearchDataType array $searchDataTypes= []) : array;

In line above I got syntax error, untill I remove SearchDataType in $searchDataTypes declarations

Thanks!

2 Answers 2

0

PHP allocates memory dynamically and what's more, it doesn't care what sort of object you store in your array. From https://stackoverflow.com/a/8759118/7703556

So you can do this check inside your function. By using array_map or array_walk See https://stackoverflow.com/a/46035743/7703556

In your case for example with array_map :

 function isInstanceOfSearchDataType($variable) {
    if(!($variable instanceof SearchDataType)) {
      throw new Exception('Variable is not instance of SearchDataType');
    }
}

public function searchSiteContent(string $s = '', bool $partial= false, $searchDataTypes= []) : array {
    array_map(isInstanceOfSearchDataType, $searchDataTypes); // do this at the beginning
  // ... code

  return $someArray;

}

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

Comments

0

You can do the following:

public function searchSiteContent(string $s = '', bool $partial= false, SearchDataType ...$searchDataTypes) : array;

Note the 3 dots before $searchDataType. This will be an array when you use it.

much simpler then having a lot of code just to validate input.

Comments

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.