3

I've this code:

const TYPE_A = 'a';
const TYPE_B = 'b';
const TYPE_C = 'c';

const TYPE_ARRAY = [
TYPE_A,
TYPE_B,
TYPE_C,
];

I use the TYPE_ARRAY to check if a type is valid by using in_array(). But I also need to do a regex check, but I can't use this array directly for that. I need a string in the form: "a|b|c", which is equivalent to:

implode('|', TYPE_ARRAY);

But in stead of doing this:

const TYPE_REGEX_STR = "a|b|c";

I wonder if it wouldn't be possible to convert the const TYPE_ARRAY automatically to a constant with the regex. So something like this:

const TYPE_REGEX_STR = implode('|', TYPE_ARRAY);

I know that this last example is not possible, but is there a another way do this?

This might seem silly, but when you have an array with many possible types, it would be better to create the const TYPE_REGEX_STR based on the const TYPE_ARRAY instead of defining it separately. In that way it would be easier to add a new type: just add it to the array and the regex string is made automatically.

Btw I need TYPE_REGEX_STR as a constant because Symfony can use a constant in the route requirements, but not a static function.

1

2 Answers 2

3

You could use define

<?php

const TYPE_A = 'a';
const TYPE_B = 'b';
const TYPE_C = 'c';

const TYPE_ARRAY = [
TYPE_A,
TYPE_B,
TYPE_C,
];

define ( 'TYPE_REGEX_STR' , implode('|', TYPE_ARRAY) );

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

1 Comment

This works worderfully, BUT it appears that Symfony can only work with class constants in the route requirement, so using define at runtime (e.g. in the __contruct function of the controller class) does not work. Pity! But thanks for your help.
2

You will want to use define

define( 'TYPE_REGEX_STR', implode('|', TYPE_ARRAY) );

2 Comments

Thanks, sounds great, but the problem is that Symfony can only use a class constant in a route requirement, and since define() is used at runtime, I can't use it for that I'm sorry to say.
Check here. Maybe you can create a class and method stackoverflow.com/questions/18079131/…

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.