0

I have a constant class in Library and I can call one of them in controller, my question, how can I call all constant values of the class in controller?

class Enum {
    const One = '1';
    const Two= '2';
}

to use:

return Enum::One; // print '1'
Tim Diekmann
  • 7,755
  • 11
  • 41
  • 69
Mikkel
  • 3
  • 1

1 Answers1

0

the easiest (albeit not necessarily the best) way would be to define them within an array as in

$const = array(
  'One'    => 1,
  'Two'    => 2,
);

Then you'd call them as $const['One'], $const['Two'], etc.

If these constants need to be available everywhere, you could set up a helper function that gets loaded on every controller that looks like this

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

function get_constants()
{
    $const = array(
        'One'          => 1,
        'Two'          => 2,
        'Copyright'    => '2018. YourCompany, LLC',
        'Creator'      => 'Your name here',
    );

    return $const;
}

Load the helper everywhere and then you can just use it like this:

$constants = get_constants();
echo $constants['Creator']; // outputs 'Your name here'

There's more standard ways, but this is by far the easiest AFAIK

Javier Larroulet
  • 3,047
  • 3
  • 13
  • 30