jcropp
jcropp

Reputation: 1246

Access Class Constants Dynamically in PHP

I want to be able to look up the value of a constant dynamically, but using a variable doesn't work with the syntax.

<?php
class Food {
    const FRUITS = 'apple, banana, orange';
    const VEGETABLES = 'spinach, carrot, celery';
}

$type = 'FRUITS';

echo Food::FRUITS;
echo Food::$type;

?>

gives

apple, banana, orange

Fatal error: Access to undeclared static property: Food::$type

How can I dynamically call the constant?

Upvotes: 2

Views: 2320

Answers (5)

Luke Manson
Luke Manson

Reputation: 21

This will be available natively in php8.3 as of November 2023

class MyClass {
    public const MY_CONST = 42;
}

$constName = 'MY_CONST';

echo MyClass::{$constName};

https://php.watch/versions/8.3/dynamic-class-const-enum-member-syntax-support

Upvotes: 2

u_mulder
u_mulder

Reputation: 54831

The only solution which comes to my head is using a constant function:

echo constant('Food::' . $type);

Here you create name of a constant, including class, as a string and pass this string ('Food::FRUITS') to constant function.

Upvotes: 9

Keval Dholakiya
Keval Dholakiya

Reputation: 1

you can create associative array

class Constants{
  const Food = [
      "FRUITS " => 'apple, banana, orange',
      "VEGETABLES" => 'spinach, carrot, celery'
  ];
}

and access value like this

$type = "FRUITS";

echo Constants::Food[$type];

Upvotes: 0

Micha&#235;l Vaes
Micha&#235;l Vaes

Reputation: 81

When using namespaces, make sure you include the namespace, even if it's autoloaded.

namespace YourNamespace;

class YourClass {
  public const HELLO = 'WORLD'; 
}

$yourConstant = 'HELLO';

// Not working
// >> PHP Warning:  constant(): Couldn't find constant YourClass::HELLO ..
constant('YourClass::' . $yourConstant);

// Working
constant('YourNamespace\YourClass::' . $yourConstant);```

Upvotes: 0

jcropp
jcropp

Reputation: 1246

A ReflectionClass can be used to get an array of all of the constants, and then the value of the specific constant can be found from there:

<?php
class Food {
    const FRUITS = 'apple, banana, orange';
    const VEGETABLES = 'spinach, carrot, celery';
}

$type = 'FRUITS';

$refClass = new ReflectionClass('Food');
$constants = $refClass->getConstants();

echo $constants[$type];

?>

Upvotes: 0

Related Questions