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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With