2

The example is following:

<?php

class test{
    const A = "1";
    const B = "2";

    public function getStr($a){
        echo self::$a;
    }

}

$c = new test();
$c->getStr("A");


 ?>

How can I echo variable "A" in the window, when I use getStr("A")

1
  • You could make a construct() function for that Commented Sep 29, 2017 at 3:52

2 Answers 2

1

It can be done with ReflectionClass::getConstants.

Try this code snippet here

<?php

ini_set('display_errors', 1);

class test{
    const A = "1";
    const B = "2";

    public function getStr($a){

        $class= new ReflectionClass(self::class);//passing class name to ReflectionClass
        echo $class->getConstant($a);//getting required constant.
    }

}

$c = new test();
$c->getStr("A");
Sign up to request clarification or add additional context in comments.

2 Comments

Will it support in PHP version 5.4
@AnkurGarg Yes it do support. You can check the documentation here php.net/manual/en/reflectionclass.getconstants.php
0

constant() is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function.

Constant Doc

echo constant("self::".$a);

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.