2

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?

1
  • I suppose you can't. Commented Jan 16, 2018 at 19:00

5 Answers 5

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah. Using a ReflectionClass to get an array of all of the constants is another way of programmatically looking up the value. I was hoping there was some obscure syntax to grab the value with a single statement/action.
2

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

1 Comment

Please post a descriptive answer and then references.
0

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];

?>

Comments

0

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);```

Comments

0

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.