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.
Related
I am new to php so please bear with me here.
I have created a class that holds a number of constants that need to be available globally to the app I am developing. However, I don't know how I can load or reference them from another class. Ideally, I would like to load in or reference the class with the constants as an array and then be able to loop through the constants to perform operations with them. Here is the structure of my constant class:
<?php
class MyConstClass {
const CONST_1 = "blah";
const CONST_2 = "blahblah";
const CONST_3 = "blahblahblah";
}
?>
Answers greatly appreciated.
Elaborate on the array concept, but just to access the constant:
echo MyConstClass::CONST_1;
If your class file is included then you can simply access values of constants like #AbraCadaver showed:
MyConstClass::CONST_1
If you want an array of constant values then I'm afraid you'll have to manually define it like this:
$constants = array(
MyConstClass::CONST_1,
MyConstClass::CONST_2,
MyConstClass::CONST_3,
);
foreach ($constants as $constant) {
// do something with $constant value
// ...
}
Or alternatively you can use reflection to list constants in a class:
$reflection = new \ReflectionClass('MyConstClass');
$constants = $reflection->getConstants();
foreach ($constants as $name => $value) {
// do something with $constant value
// ...
}
However, remember that reflection is always slow.
I have a file that defines constant variables, like this:
define_vars.php
<?
define("something","value");
define("something1","value");
define("something2","value");
define("something3","value");
And I have a function which parses $var as the constant variable name, like this:
function something($var=''){
include('define_vars.php');
// $var is the name of one of the variables I am defining in the other file (define_vars.php)
// So $var may have a value of "something3", which is the name of one of the constants defined in the other file...
}
I need to somehow get the value of the constant, when $var holds the name of the constant I wish to get the value of....make sense? :S
Any Ideas?
http://php.net/constant
function something($var) {
if (defined($var)) {
$value = constant($var);
}
}
Also you should make sure that the file with the definitions gets included only once, so use require_once('define_vars.php'); instead.
You want constant()
constant($var); // value
Use constant() to get the value. You could do something like this
function something($var = '') {
include_once('define_vars.php'); //you don't want to include the file more than once or it will cause a fatal error when trying to redefine your constants
return (defined($var) ? constant($var) : null);
}
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.
define('VAR_1', 'Some info 01');
define('VAR_2', 'Some info 02');
define('VAR_3', 'Some info 03');
define('VAR_4', 'Some info 04');
define('VAR_5', 'Some info 05');
define('VAR_6', 'Some info 06');
define('VAR_7', 'Some info 07');
I usually namespace my constants, if I've got many of them, in a class like so:
class Foo {
const Bar = 1;
const Baz = 2;
public static $array = array(1,2,3);
}
echo Foo::Bar; # Accessing the constants
print_r(Foo:$array);
Putting an Array in a constant is not possible for class constants, and I don't think it is a good practice putting them in global constants either, if it is even possible (not sure). Maybe you should tell us what you are trying to accomplish, maybe there is a better way to do it.
Oh, and please don't do something like this:
for($x=0; x<10; $x++) {
define('VAR_' . $x, 'Information #' . $x);
}
Which has been suggested here, but IMHO this is absolutely not how constant are supposed to be used.
You can use an array and a loop to accomplish this.
Do you mean you want a single constant with multiple values stored internally?
You can set an array as a constant:
define('VAR', array('Some info 01','Some info 02',...));
In this way, VAR[0] == 'Some info 01', VAR[1] == 'Some info 02', etc.
Is this what you wanted?
You can't define constants with arrays. Thanks to #wiseguy for reminding me.
as already stated it is advised that you encapsulate your constants so that it does not overflow your root scope, try create a class and set your constants in that, such as:
final abstract class Constants
{
const FOO = 'a';
const BAR = 1;
const ZED = 'c';
}
And then simply use like use like so:
echo Constants::FOO;
You should not really be using constants for storing arrays, which is why it has not been allowed within the PHP core.
but im not here to question your motives so if you want to store arrays within a constants then you can do so by transforming into a string, such as
define('MY_ARRAY',serialize(array(1 => 'foo')));
and then run unserialize to get it back into an array
i have something like
define("__ROOT_PATH__", "http://{$_SERVER['HTTP_HOST']}/admin");
within a class. how do i call it from within functions is it with a cologn? i tried looking it up on google but nothing.
thanks
The function define() is intended for global constants, so you just use the string __ROOT_PATH__ (I would recommend using another naming scheme, though. Constants starting with two underscores are reserved by PHP for their magic constants)
define('__ROOT_PATH__', 'Constant String');
echo __ROOT_PATH__;
If you want to declare a class constant, use the const keyword:
class Test {
const ROOT_PATH = 'Constant string';
}
echo Test::ROOT_PATH;
There is one problem though: The class constants are evaluated while your script is being parsed, so you cannot use other variables within these constants (so your example will not work). Using define() works, as it is treated like any other function and the constant value can be defined dynamically.
EDIT:
As PCheese pointed out, you can access class constants using the keyword self, instead of the class name from within the class:
class Test {
const ROOT_PATH = 'Constant string';
public function foo() {
echo self::ROOT_PATH;
}
}
# You must use the class' name outside its scope:
echo Test::ROOT_PATH;
Using define will define the constant globally, so just refer to it directly in your code:
echo __ROOT_PATH__;
If you want to scope a constant to a class, you need to declare it differently. However, this syntax will not let you declare it dynamically as you did above, using $_SERVER.
<?php
class MyClass {
const MY_CONST = "foo";
public function showConstant() {
echo self::MY_CONST;
}
}
// Example:
echo MyClass::MY_CONST;
$c = new MyClass();
$c->showConstant();
Simply use the name of the constant.
i.e.
echo "Root path is " . __ROOT_PATH__;