1

I would like to be able to pass enums to functions. I know PHP doesn't support them per se, but there are instances where an enum would make sense.

For instance, take: function doPayment($payment_method = 'paypal') { // ... code goes here }

You can call it via doPayment('paypal'), doPayment(), doPayment('creditcard'), or doPayment('creditcadr');

This introduces the chance of typos plus it's a pain to keep strings consistent and to debug. We could pass them as ints such as doPayment(2) but that's ugly and we'd have to keep track of them or put them in defines, which is the next example: doPayment(PAYMENT_METHOD_PAYPAL); but then we'd have to put the define in some global file that is accessible by all. Also I find that you end up with a class of hundreds of defines and it's hard to keep track of what belongs to what.

Meanwhile in Java, it's easy:

doPayment(PaymentClass.PaymentMethod.PayPal); // or doPayment(PaymentMethod.PayPal);

That's really what I'm looking for if possible. I guess I could create an external class for each set of enums but that adds a lot of files as well (while the Java example you can create an enum within the parent class).

I was wondering if Laravel has added a method to do this, if it's not doable in PHP.

1 Answer 1

2

You could do something like:

class PaymentMethod extends SplEnum {
    const __default = 1;
    // Our enum values
    const PAYPAL    = 1;
    const IDEAL     = 2;
    //..etc
}

Then, calling your function:

doPayment(PaymentMethod::PAYPAL);

Laravel is properly namespaced, so I would go on to create a helper class and add this to the autoloader, this way you just need to include the namespace as a "use" in top of the Controllers where you want to use it. You can also add the path to the class in your project's composer.json file

an example from composer documentation:

{
    "autoload": {
        "psr-4": {
            "Monolog\\": "src/",
            "helper\\": "path/to/helpers"
        }
    }
}
Sign up to request clarification or add additional context in comments.

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.