PHP - Using a string to get a constant? [duplicate] - php

I am trying to create a constant name dynamically and then get at the value.
define( CONSTANT_1 , "Some value" ) ;
// try to use it dynamically ...
$constant_number = 1 ;
$constant_name = ("CONSTANT_" . $constant_number) ;
// try to assign the constant value to a variable...
$constant_value = $constant_name;
But I find that $constant value still contains the NAME of the constant, and not the VALUE.
I tried the second level of indirection as well $$constant_name But that would make it a variable not a constant.
Can somebody throw some light on this?

http://dk.php.net/manual/en/function.constant.php
echo constant($constant_name);

And to demonstrate that this works with class constants too:
class Joshua {
const SAY_HELLO = "Hello, World";
}
$command = "HELLO";
echo constant("Joshua::SAY_$command");

To use dynamic constant names in your class you can use reflection feature (since php5):
$thisClass = new ReflectionClass(__CLASS__);
$thisClass->getConstant($constName);
For example:
if you want to filter only specific (SORT_*) constants in the class
class MyClass
{
const SORT_RELEVANCE = 1;
const SORT_STARTDATE = 2;
const DISTANCE_DEFAULT = 20;
public static function getAvailableSortDirections()
{
$thisClass = new ReflectionClass(__CLASS__);
$classConstants = array_keys($thisClass->getConstants());
$sortDirections = [];
foreach ($classConstants as $constName) {
if (0 === strpos($constName, 'SORT_')) {
$sortDirections[] = $thisClass->getConstant($constName);
}
}
return $sortDirections;
}
}
var_dump(MyClass::getAvailableSortDirections());
result:
array (size=2)
0 => int 1
1 => int 2

Related

PHP enumeration with variable [duplicate]

I am trying to create a constant name dynamically and then get at the value.
define( CONSTANT_1 , "Some value" ) ;
// try to use it dynamically ...
$constant_number = 1 ;
$constant_name = ("CONSTANT_" . $constant_number) ;
// try to assign the constant value to a variable...
$constant_value = $constant_name;
But I find that $constant value still contains the NAME of the constant, and not the VALUE.
I tried the second level of indirection as well $$constant_name But that would make it a variable not a constant.
Can somebody throw some light on this?
http://dk.php.net/manual/en/function.constant.php
echo constant($constant_name);
And to demonstrate that this works with class constants too:
class Joshua {
const SAY_HELLO = "Hello, World";
}
$command = "HELLO";
echo constant("Joshua::SAY_$command");
To use dynamic constant names in your class you can use reflection feature (since php5):
$thisClass = new ReflectionClass(__CLASS__);
$thisClass->getConstant($constName);
For example:
if you want to filter only specific (SORT_*) constants in the class
class MyClass
{
const SORT_RELEVANCE = 1;
const SORT_STARTDATE = 2;
const DISTANCE_DEFAULT = 20;
public static function getAvailableSortDirections()
{
$thisClass = new ReflectionClass(__CLASS__);
$classConstants = array_keys($thisClass->getConstants());
$sortDirections = [];
foreach ($classConstants as $constName) {
if (0 === strpos($constName, 'SORT_')) {
$sortDirections[] = $thisClass->getConstant($constName);
}
}
return $sortDirections;
}
}
var_dump(MyClass::getAvailableSortDirections());
result:
array (size=2)
0 => int 1
1 => int 2

PHP how to echo two variables [duplicate]

I am trying to create a constant name dynamically and then get at the value.
define( CONSTANT_1 , "Some value" ) ;
// try to use it dynamically ...
$constant_number = 1 ;
$constant_name = ("CONSTANT_" . $constant_number) ;
// try to assign the constant value to a variable...
$constant_value = $constant_name;
But I find that $constant value still contains the NAME of the constant, and not the VALUE.
I tried the second level of indirection as well $$constant_name But that would make it a variable not a constant.
Can somebody throw some light on this?
http://dk.php.net/manual/en/function.constant.php
echo constant($constant_name);
And to demonstrate that this works with class constants too:
class Joshua {
const SAY_HELLO = "Hello, World";
}
$command = "HELLO";
echo constant("Joshua::SAY_$command");
To use dynamic constant names in your class you can use reflection feature (since php5):
$thisClass = new ReflectionClass(__CLASS__);
$thisClass->getConstant($constName);
For example:
if you want to filter only specific (SORT_*) constants in the class
class MyClass
{
const SORT_RELEVANCE = 1;
const SORT_STARTDATE = 2;
const DISTANCE_DEFAULT = 20;
public static function getAvailableSortDirections()
{
$thisClass = new ReflectionClass(__CLASS__);
$classConstants = array_keys($thisClass->getConstants());
$sortDirections = [];
foreach ($classConstants as $constName) {
if (0 === strpos($constName, 'SORT_')) {
$sortDirections[] = $thisClass->getConstant($constName);
}
}
return $sortDirections;
}
}
var_dump(MyClass::getAvailableSortDirections());
result:
array (size=2)
0 => int 1
1 => int 2

Define const as a variable

I looked up a few solutions, but nothing that's able to solve it. I realize that constants are not supposed to be modifiable hence the whole point of the word "constant".
In this case I'm dealing with an API class that goes like this
class GetAdGroups {
const CAMPAIGN_ID = "";
I have to pass a value to CAMPAIGN_ID, but it can't be hard coded as a string.
So the following is not an option:
const CAMPAIGN_ID = 123;
I tried going with "define"
class GetAdGroups {
$my_var = 123;
define("CAMPAIGN_ID", "$my_var");
But it throws an error and when I define it outside the class scope, it also throws an error that the constant is not found.
Not sure what else to try. Pretty new to OOP and would appreciate your help
Check this what are new features in php 5.6
<?php
const ONE = 1;
const TWO = ONE * 2;
class C {
const THREE = TWO + 1;
const ONE_THIRD = ONE / self::THREE;
const SENTENCE = 'The value of THREE is '.self::THREE;
public function f($a = ONE + self::THREE) {
return $a;
}
}
echo (new C)->f()."\n";
echo C::SENTENCE;
?>
this may help you. You can use expression as constant value here.
Note:-
It is now possible to provide a scalar expression involving numeric
and string literals and/or constants in contexts where PHP previously
expected a static value, such as constant and property declarations
and default function arguments.
Yes, this is quite impossible, even you can not do like
function bar(){
return 'Hi';
}
class C {
const SENTENCE = bar();
//const SENTENCE = :SELF:foo();
public static foo(){
return "Hello';
}
}
echo C::SENTENCE;
#u_mulder is very correct.
You have missed reading the documentation correctly.
/**
* This example gets all ad groups in a campaign. To get campaigns, run
* GetCampaigns.php.
*/
Check this class instead.
here your campaign id is variable.
foreach ($page->getEntries() as $campaign) {
printf(
"Campaign with ID %d and name '%s' was found.\n",
$campaign->getId(),
$campaign->getName()
);
}
If you are using PHP 7+ then you can use this way .
// Works as of PHP 7
define('ALLVAR', array(
'dog',
'cat',
'bird'
));
echo ALLVAR[1]; // outputs "cat"
If you are using php < 7 Then use this way .
define ("ALLVAR", serialize (array ('dog','cat','bird')));
$my_const = unserialize(ALLVAR);
Inside your Class you can define a function for constants. Like below
class GetAdGroups{
public $options = array(
'app_id' => 'hello',
);
public function getConstant($key){
return $this->options[$key];
}
}
$a = new GetAdGroups();
print_r($a->getConstant('app_id'));

Dynamic constant name in PHP

I am trying to create a constant name dynamically and then get at the value.
define( CONSTANT_1 , "Some value" ) ;
// try to use it dynamically ...
$constant_number = 1 ;
$constant_name = ("CONSTANT_" . $constant_number) ;
// try to assign the constant value to a variable...
$constant_value = $constant_name;
But I find that $constant value still contains the NAME of the constant, and not the VALUE.
I tried the second level of indirection as well $$constant_name But that would make it a variable not a constant.
Can somebody throw some light on this?
http://dk.php.net/manual/en/function.constant.php
echo constant($constant_name);
And to demonstrate that this works with class constants too:
class Joshua {
const SAY_HELLO = "Hello, World";
}
$command = "HELLO";
echo constant("Joshua::SAY_$command");
To use dynamic constant names in your class you can use reflection feature (since php5):
$thisClass = new ReflectionClass(__CLASS__);
$thisClass->getConstant($constName);
For example:
if you want to filter only specific (SORT_*) constants in the class
class MyClass
{
const SORT_RELEVANCE = 1;
const SORT_STARTDATE = 2;
const DISTANCE_DEFAULT = 20;
public static function getAvailableSortDirections()
{
$thisClass = new ReflectionClass(__CLASS__);
$classConstants = array_keys($thisClass->getConstants());
$sortDirections = [];
foreach ($classConstants as $constName) {
if (0 === strpos($constName, 'SORT_')) {
$sortDirections[] = $thisClass->getConstant($constName);
}
}
return $sortDirections;
}
}
var_dump(MyClass::getAvailableSortDirections());
result:
array (size=2)
0 => int 1
1 => int 2

Using constants as default function values in PHP

Is this legal?
<?php
function ftw($foo = 'pwnage', $nub = MENU_DEFAULT_VALUE, $odp = ODP_DEFAULT_VALUE) {
//lots_of_awesome_code
}
?>
where MENU_DEFAULT_VALUE and ODP_DEFAULT_VALUE are constants defined previously in the file.
Yes, that is legal.
From the manual:
The default value must be a constant
expression, not (for example) a
variable, a class member or a function
call.
Constants fit that bill perfectly.
In an OOP context, you can also use a class member constant as a default method argument value.
class MyClass
{
const A = 1;
public function __construct($arg = self::A)
{
echo $arg;
}
}
why don't you try ?
Still, just in case you can test right now, the following code :
define('MENU_DEFAULT_VALUE', 10);
define('ODP_DEFAULT_VALUE', 'hello');
function ftw($foo = 'pwnage', $nub = MENU_DEFAULT_VALUE, $odp = ODP_DEFAULT_VALUE) {
var_dump($foo);
var_dump($nub);
var_dump($odp);
}
ftw();
gives this output :
string 'pwnage' (length=6)
int 10
string 'hello' (length=5)
So I'd say that, yes, it is valid :-)

Categories