PHP Static class has a very long name - can I use a shorter pointer?
-
12-04-2021 - |
Pergunta
I have a static class with a very long name, example:
class SomeClassWithAVeryLongName {
const CONST_ONE = 'foo';
const CONST_TWO = 'bar';
}
In my other class, I want to reference these constants. The problem is there are a bunch of them and I use them as associative keys so my code gets very verbose:
$someArray[SomeClassWithAVeryLongName::CONST_ONE][SomeClassWithAVeryLongName::CONST_TWO] = 'foobar';
Is there a way I can use a pointer of some kind? Something like:
// Pseudo code
$scwavln = 'SomeClassWithAVeryLongName';
$someArray[$scwavln::CONST_ONE][$scwavln::CONST_TWO] = 'foobar';
It doesn't seem to be working for me. I'm on PHP 5.2.6.
Solução
class scwavln extends SomeClassWithAVeryLongName {}
$someArray[scwavln::CONST_ONE][scwavln::CONST_TWO] = 'foobar';
Outras dicas
Well, for the specific problem just assign the constant values to a shorter variable and use that as your index key.
$index1 = SomeClassWithAVeryLongName::CONST_ONE;
$index2 = SomeClassWithAVeryLongName::CONST_TWO;
$someArray[$index1][$index2] = 'foo';
However, you can do what you were attempting to do with PHP 5.3:
$Uri = '\\My\\Namespaced\\Class';
// you see the value of the const
var_dump($Uri::MY_CONST);
class SomeClassWithAVeryLongName {
const CONST_ONE = 'foo';
const CONST_TWO = 'bar';
}
$rfl = new ReflectionClass("SomeClassWithAVeryLongName");
$props = $rfl->getConstants();
print_r( $props );
Array
(
[CONST_ONE] => foo
[CONST_TWO] => bar
)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow