How can I access class constants within a function that is defined inside that class?
class Test{
const STATUS_ENABLED = 'Enabled';
const STATUS_DISABLED = 'Disabled';
public function someMethod(){
//how can I access ALL the constants here let's say in a form of array
}
}
I don't mean to access each constant but rather access ALL the constants in a form of array. I saw something like:
<?php
class Profile {
const LABEL_FIRST_NAME = "First Name";
const LABEL_LAST_NAME = "Last Name";
const LABEL_COMPANY_NAME = "Company";
}
$refl = new ReflectionClass('Profile');
print_r($refl->getConstants());
But what if I want to access ALL the list of constants inside that class?
To get a list of all the defined constants for a class, you'll need to use Reflection:
The ReflectionClass object has a getConstants() method
If you want to collect all the constants as an array, you could use Reflection:
$reflection = new ReflectionClass("classNameGoesHere");
$reflection->getConstants();
However, this would be very slow and mostly pointless. What would be a much better idea, is to simply declare all of the constants in another array, which you then use:
class Test{
const STATUS_ENABLED = 'Enabled';
const STATUS_DISABLED = 'Disabled';
$states = array(
self::STATUS_ENABLED,
self::STATUS_DISABLED,
}
This has the added advantage that it'll keep working if you add more constants. There's no reason to assume all of a class' constants are related in any way, unless you explicitly make it so by defining the relation as an array.