Php class get all const

Php class get all const

It is possible to define constants on a per-class basis remaining the same and unchangeable. The default visibility of class constants is public .

Note:

Class constants can be redefined by a child class. As of PHP 8.1.0, class constants cannot be redefined by a child class if it is defined as final.

It’s also possible for interfaces to have constants . Look at the interface documentation for examples.

It’s possible to reference the class using a variable. The variable’s value can not be a keyword (e.g. self , parent and static ).

Note that class constants are allocated once per class, and not for each class instance.

Example #1 Defining and using a constant

class MyClass
const CONSTANT = ‘constant value’ ;

function showConstant () echo self :: CONSTANT . «\n» ;
>
>

echo MyClass :: CONSTANT . «\n» ;

$classname = «MyClass» ;
echo $classname :: CONSTANT . «\n» ;

$class = new MyClass ();
$class -> showConstant ();

The special ::class constant allows for fully qualified class name resolution at compile time, this is useful for namespaced classes:

Example #2 Namespaced ::class example

Example #3 Class constant expression example

const ONE = 1 ;
class foo const TWO = ONE * 2 ;
const THREE = ONE + self :: TWO ;
const SENTENCE = ‘The value of THREE is ‘ . self :: THREE ;
>
?>

Example #4 Class constant visibility modifiers, as of PHP 7.1.0

class Foo public const BAR = ‘bar’ ;
private const BAZ = ‘baz’ ;
>
echo Foo :: BAR , PHP_EOL ;
echo Foo :: BAZ , PHP_EOL ;
?>

Output of the above example in PHP 7.1:

bar Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …

Note:

As of PHP 7.1.0 visibility modifiers are allowed for class constants.

User Contributed Notes 12 notes

it’s possible to declare constant in base class, and override it in child, and access to correct value of the const from the static method is possible by ‘get_called_class’ method:
abstract class dbObject
<
const TABLE_NAME = ‘undefined’ ;

public static function GetAll ()
$c = get_called_class ();
return «SELECT * FROM `» . $c :: TABLE_NAME . «`» ;
>
>

class dbPerson extends dbObject
const TABLE_NAME = ‘persons’ ;
>

class dbAdmin extends dbPerson
const TABLE_NAME = ‘admins’ ;
>

echo dbPerson :: GetAll (). «
» ; //output: «SELECT * FROM `persons`»
echo dbAdmin :: GetAll (). «
» ; //output: «SELECT * FROM `admins`»

As of PHP 5.6 you can finally define constant using math expressions, like this one:

class MyTimer const SEC_PER_DAY = 60 * 60 * 24 ;
>

Most people miss the point in declaring constants and confuse then things by trying to declare things like functions or arrays as constants. What happens next is to try things that are more complicated then necessary and sometimes lead to bad coding practices. Let me explain.

A constant is a name for a value (but it’s NOT a variable), that usually will be replaced in the code while it gets COMPILED and NOT at runtime.

So returned values from functions can’t be used, because they will return a value only at runtime.

Arrays can’t be used, because they are data structures that exist at runtime.

One main purpose of declaring a constant is usually using a value in your code, that you can replace easily in one place without looking for all the occurences. Another is, to avoid mistakes.

Think about some examples written by some before me:

1. const MY_ARR = «return array(\»A\», \»B\», \»C\», \»D\»);»;
It was said, this would declare an array that can be used with eval. WRONG! This is just a string as constant, NOT an array. Does it make sense if it would be possible to declare an array as constant? Probably not. Instead declare the values of the array as constants and make an array variable.

2. const magic_quotes = (bool)get_magic_quotes_gpc();
This can’t work, of course. And it doesn’t make sense either. The function already returns the value, there is no purpose in declaring a constant for the same thing.

3. Someone spoke about «dynamic» assignments to constants. What? There are no dynamic assignments to constants, runtime assignments work _only_ with variables. Let’s take the proposed example:

/**
* Constants that deal only with the database
*/
class DbConstant extends aClassConstant <
protected $host = ‘localhost’ ;
protected $user = ‘user’ ;
protected $password = ‘pass’ ;
protected $database = ‘db’ ;
protected $time ;
function __construct () <
$this -> time = time () + 1 ; // dynamic assignment
>
>
?>

Those aren’t constants, those are properties of the class. Something like «this->time = time()» would even totally defy the purpose of a constant. Constants are supposed to be just that, constant values, on every execution. They are not supposed to change every time a script runs or a class is instantiated.

Conclusion: Don’t try to reinvent constants as variables. If constants don’t work, just use variables. Then you don’t need to reinvent methods to achieve things for what is already there.

I think it’s useful if we draw some attention to late static binding here:
class A const MY_CONST = false ;
public function my_const_self () return self :: MY_CONST ;
>
public function my_const_static () return static:: MY_CONST ;
>
>

class B extends A const MY_CONST = true ;
>

$b = new B ();
echo $b -> my_const_self ? ‘yes’ : ‘no’ ; // output: no
echo $b -> my_const_static ? ‘yes’ : ‘no’ ; // output: yes
?>

const can also be used directly in namespaces, a feature never explicitly stated in the documentation.

const BAR = 1 ;
?>

# bar.php
require ‘foo.php’ ;

var_dump ( Foo \ BAR ); // => int(1)
?>

Hi, i would like to point out difference between self::CONST and $this::CONST with extended class.
Let us have class a:

class a <
const CONST_INT = 10 ;

public function getSelf () return self :: CONST_INT ;
>

public function getThis () return $this :: CONST_INT ;
>
>
?>

And class b (which extends a)

class b extends a const CONST_INT = 20 ;

public function getSelf () return parent :: getSelf ();
>

public function getThis () return parent :: getThis ();
>
>
?>

Both classes have same named constant CONST_INT.
When child call method in parent class, there is different output between self and $this usage.

print_r ( $b -> getSelf ()); //10
print_r ( $b -> getThis ()); //20

Источник

ReflectionClass::getConstants

Gets all defined constants from a class, regardless of their visibility.

Parameters

The optional filter, for filtering desired constant visibilities. It’s configured using the ReflectionClassConstant constants, and defaults to all constant visibilities.

Return Values

An array of constants, where the keys hold the name and the values the value of the constants.

Changelog

See Also

User Contributed Notes 6 notes

If you want to return the constants defined inside a class then you can also define an internal method as follows:

class myClass const NONE = 0 ;
const REQUEST = 100 ;
const AUTH = 101 ;

static function getConstants () $oClass = new ReflectionClass ( __CLASS__ );
return $oClass -> getConstants ();
>
>
?>

You can pass $this as class for the ReflectionClass. __CLASS__ won’t help if you extend the original class, because it is a magic constant based on the file itself.

class Example const TYPE_A = 1 ;
const TYPE_B = ‘hello’ ;

public function getConstants ()
$reflectionClass = new ReflectionClass ( $this );
return $reflectionClass -> getConstants ();
>
>

$example = new Example ();
var_dump ( $example -> getConstants ());

// Result:
array ( size = 2 )
‘TYPE_A’ => int 1
‘TYPE_B’ => (string) ‘hello’

If you want to define a static getConstants() function which works with inheritance you can do the following:

abstract class AbstractClass
const TEST = «test» ;

public static function getConstants ()
// «static::class» here does the magic
$reflectionClass = new ReflectionClass (static::class);
return $reflectionClass -> getConstants ();
>
>

class ChildClass extends AbstractClass
const TYPE_A = 1 ;
const TYPE_B = ‘hello’ ;
>

$example = new ChildClass ();
var_dump ( $example -> getConstants ());

// Result:
array( 3 ) ‘TYPE_A’ => int ( 1 )
‘TYPE_B’ => string ( 5 ) «hello»
‘TEST’ => string ( 4 ) «test»
>

I use a functions to do somthing base on the class constant name as below. This example maybe helpful for everybody.
public function renderData ( $question_type = NULL , $data = array()) $types = array();
$qt = new ReflectionClass ( questionType );
$types = $qt -> getConstants ();
if ( $type = array_search ( $question_type , $types )) //. Do somthing
>
>
?>

I was trying to determine how to get a var_dump of constants that are within an interface. Thats right, not using any classes but the interface itself.

Along my travels I found it quite interesting that the ReflectionClass along with a direct call to the interface will also dump its constants. Perfect.

This was using PHP 5.3.1 and my example as below:-

$oClass = new ReflectionClass (‘MyConstants’);
$array = $oClass->getConstants ();
var_dump ($array);
unset ($oClass);
?>

what you would get from the command line:-

?:\. \htdocs\. >php test.php
array(2) [«DEBUG_MODE_ACTIVE»]=> bool(false)
[«PHP_VERSION_REQUIREMENT»]=> string(5) «5.1.2»

But as you can see this can work quite well to your advantage in many ways so I truely hope this helps someone else with a similar headache in the future to come!

Get the latest constants declared.

abstract class AbstractEnum
/**
* Возвращает все константы класса || Return all constants
*
* @return array
*/
static function getConstants()
$rc = new \ReflectionClass(get_called_class());

/**
* Возвращает массив констант определенные в вызываемом классе || Return last constants
*
* @return array
*/
static function lastConstants()
$parentConstants = static::getParentConstants();

return array_diff($allConstants, $parentConstants);
>

/**
* Возвращает все константы родительских классов || Return parent constants
*
* @return array
*/
static function getParentConstants()
$rc = new \ReflectionClass(get_parent_class(static::class));
$consts = $rc->getConstants();

======
class Roles extends AbstractEnum
const ROOT = ‘root’;
const ADMIN = ‘admin’;
const USER = ‘user’;
>

// Output:
All: root, admin, user
Last: root, admin, user

class NewRoles extends Roles
const CLIENT = ‘client’;
const MODERATOR = ‘moderator’;
const SUPERMODERATOR = ‘super’.self::USER;
>

// Output:
All: client, moderator, superuser, root, admin, user
Last: client, moderator, superuser

class AdditionalRoles extends Roles
const VIEWER = ‘viewer’;
const CHECKER = ‘checker’;
const ROOT = ‘rooter’;
>

All: viewer, checker, rooter, client, moderator, superuser, admin, user
Last: viewer, checker, rooter

Оцените статью