Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a file that defines constants in a class (and it's scope)

Say we have the following:

some.class.php

class
{
    public __construct()
    {
        fun_stuff();
    }

}

configuration.inc

const SOMECONST = 1;
const SOMEOTHERCONST = 2;

I am looking to do something like this:

some.class.php

class
{
    public __construct()
    {
        include_once(configuration.inc);
        fun_stuff();
    }

}

Now this works, but the constant is not defined within the scope of the class (echo some::SOMECONST;) but rather in the global scope (echo SOMECONST;)

I really really want to have the constants in another file as it makes a lot of sense in my case. Is there a way to declare the constants in the scope of the class? I know it's impossible to use includes or requires inside the class definition so i'm at a loss.

like image 693
Matthew Goulart Avatar asked Mar 13 '23 11:03

Matthew Goulart


1 Answers

Simplest possibilty is to define your constant in one class and let your other class extend that class.

class myClassConstant {
  const SOMECONST = 1;
  const SOMEOTHERCONST = 2;
}

class myClass extends myClassConstant {

  public function __construct() {
    echo self::SOMECONST . ' + ' . self::SOMEOTHERCONST . ' = 3';
  }
}

$obj = new myClass(); // Output: 1 + 2 = 3

If you are using php autoloader this can easily be split up into two different files.

like image 135
maxhb Avatar answered Mar 16 '23 04:03

maxhb