Is it possible to expose an enumeration as a class property?

286 Views Asked by At

I have a couple enumerations that are private to a particular class. I originally had them in the same file as my class but, along with my confusion on PSR-4 autoloading, this was causing headaches. In addition, it didn't seem to follow the PSR-4 spec (I think). I can separate them into different files but for now, I don't particularly like that approach. I'd prefer the code all be together.

<?php

enum MODAL_SIZE {
    case SM;
    case DEFAULT;
    case LG;
    case XL;

    public function class() {
        return $this === MODAL_SIZE::DEFAULT ? '' : 'modal-' . strtolower($this->name);
    }
}

enum LAUNCH_TYPES {
    case BUTTON;
    case ANCHOR;
}

class modal {
    public LAUNCH_TYPES $launch_type;
    public MODAL_SIZE $size;

    // Implementation
    public function launcher(LAUNCH_TYPES $type = LAUNCH_TYPES::BUTTON, array $attrs = []) : string {
        // function's body
    }
}

$modal = new modal();

// error is thrown here
$modal->launcher($modal->launch_type::ANCHOR, ['text' => $rule[$label]])

My next thought is to simply expose the enumeration via the class as a property. My editor seems to think this works as the autocomplete is as I would expect, however executing the code results in:

Fatal error: Uncaught Error: Typed property bootstrap\modal::$launch_type must not be accessed before initialization

Am I being too picky here? Right now, I have a single modal.class.php file under a directory named bootstrap. I'd have to create a new subdirectory named modal and then have the modal.class.php file define the namespace as bootstrap\modal which would repeat the class name in my use statements. Then separate files for each enumeration within the bootstrap\modal namespace/directory.

0

There are 0 best solutions below