How to access a class const dynamically in PHP? - php

Let's say I have a class like so:
class Order {
const STATUS_INITIALIZED = 'initialized';
const STATUS_ORDERED = 'ordered';
}
and I'd like to grab the constant like so:
$status = $_GET['status']; // ?status=STATUS_ORDERED
Is there a way to access the value of the constant, given the name of the constant as a string?
I've tried:
Order::$status
Order::$$status

The function constant does this. The syntax is
constant('Order::'.$status)
See it in action.

Related

Access constants inside namespace with a dynamic name

Lets say i have 2 php files with namespaces :
The first:
# src/one.php
namespace foo\one;
const SOME_VALUE = "value 1";
And the second:
# src/two.php
namespace foo\two;
const SOME_VALUE = "value 2";
What i am trying to do :
require_once "src/one.php";
require_once "src/two.php";
foreach(["one", "two"] as $ns_type) {
echo foo\$ns_type\SOME_VALUE;
}
Obviously it does not work like that. I have been reading the doc's and could
not find the right way to do this.
The only solution i found is to add a function to each namespace, construct a string with it's name and then call it.
$func = "foo\$ns_name\get_my_constant";
$func();
So the question remains, how can i access namespaced constants without a helper function ?
P.S constant names are same for each file
If you need to print constant value by it's dynamic name, you can try this:
echo constant("foo\\$ns_type\SOME_VALUE");
in your foreach loop.

Assign value to php class const

I am not at all good in oop concept but i tried
final class my_class
{
const VALUE = "test";
const VALUE1 = "test";
}
this is working
$some = 'test';
final class my_class
{
const VALUE = $some;
const VALUE1 = "test";
}
this is not working why?
Because PHP5 currently doesn't support this.
If you want this feature, you have to wait for PHP5.6 which added constant scalar expressions: https://wiki.php.net/rfc/const_scalar_exprs
That means, you can use constant scalar expressions to define constants - something like const VALUE = $var; still wont work for some good reasons.
If you really want to define some runtime constants, you have to use define() or manipulate classes with runkit(runkit_constant_add)

PHP Object access with class constant

Is it possible in PHP to access a member of an object where the name of the member is specified by a class constant?
Consider this example:
class X{
const foo = "abc";
}
class Y{
public $abc;
}
$y = new Y();
$y->X::foo = 23; //This does not work
The parser doesn't accept the last line but this is what I want. I want to access the field with the name stored in the class constant X::foo. Is there a syntax to achieve that?
Use variable variables, either via a temp or directly:
$name = X::foo; // Via temp var
$y->$name = 23; // Access the member by the string's content
var_dump($y->{X::foo}); // Dumps 23
Working sample here.
You should write your code like this
$y->{X::foo} = 23;
Hope it helps

PHP: Can't assign a constant in a function?

I have a function called getSources(); In this function I want to easily assign numbers to constants. I figured this would work:
const A = 1;
const B = 2;
const C = 3;
const D = 4;
And I could just do this:
$someValue = A;
But it doesn't work. What am I missing? I don't want these variables to be used outside of the scope of this function.
Use define instead.
define('A', 1);
try
define('myname', 'myvalue');
echo myname;
// Output
myvalue
You need to use the scope resolution operator (::) to access them (if they're setup as const for a class).
Otherwise, you need to use define() which makes the identifiers global.
you can do like this
function getSources()
{
define(A,1);
define(B,2);
....
}
like this you can solve it

ReflectionClass::getDefaultProperties() and class constants

I am using Reflection against the following class:
class Constant {
const CONSTANT = 3;
public $test1 = 'CONSTANT';
public $test2 = CONSTANT;
}
When using ReflectionClass::getDefaultProperties(); I get the following notice:
PHP Notice: Use of undefined constant CONSTANT - assumed 'CONSTANT'
on this line of code:
$defaultValues = $reflectionClass->getDefaultProperties();
First, I wonder why I get the notice here (I mean, I can't anticipate/avoid the notice even though the code is 100% correct)?
And second, when using var_export($defaultValues[3]), it outputs 'CONSTANT' which is normal because it has been casted to string.
So, how can I output CONSTANT instead of 'CONSTANT' for $test2 and still output a quote-delimited string for $test1?
Edit: I get CONSTANT for both cases ($test1 and $test2) but because of that I can't differentiate between them. I want to be able to know: that is a string, or that is the name of a constant.
why I get the notice here?
because you mean self::CONSTANT but tried to use global CONSTANT, e.g. your code assumes
const CONSTANT = 3; // global constant
class Constant {
const CONSTANT = 3; // class constant
public $test1 = 'CONSTANT';
public $test2 = CONSTANT; // refers to global constant
}
but you wanted to do this:
class Constant {
const CONSTANT = 3;
public $test1 = 'CONSTANT';
public $test2 = self::CONSTANT; // self indicated class scope
}
With the latter, this
$reflectionClass = new ReflectionClass('Constant');
var_dump( $reflectionClass->getDefaultProperties() );
will give
array(2) {
["test1"]=>
string(8) "CONSTANT"
["test2"]=>
int(3)
}
Is there a way to get ["test2"] => self::CONSTANT via Reflection? No. The Reflection API will evaluate the constant. If you want self::CONSTANT you'd have to try some of the 3rd party static reflection APIs.
And obviously, if you want 'CONSTANT', write "'CONSTANT'".
Regarding EDIT:
I get CONSTANT for both cases ($test1 and $test2) but because of that I can't differentiate between them. I want to be able to know: that is a string, or that is the name of a constant.
$foo = CONSTANT means assign the constant value to the foo property. It does not mean assign the constant itself. By assigning the value to a property, it no longer is a constant value. It's mutable. The "name of a constant" is represented as a string. You can use ReflectionClass::hasConstant to check whether that string happens to also be the name of a defined constant in the class or use defined for global constants.
Since you use CONSTANT for the value of $test2 and do not define it before it will throw the "undefined constant" error. Do you want to use the class constant CONSTANT as value for the public $test2? Then use public $test2 = self::CONSTANT. Otherwise define CONSTANT as constant before the class.
Please note that PHP casts all unknown constants as strings with the value of the name of the unknown constant.

Categories