PHP enumeration with variable [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 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

PHP - Using a string to get a constant? [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'));

Passing named parameters to a php function through call_user_func_array

When trying to call a function in a child class with an arbitrary set of parameters, I'm having the following problem:
class Base{
function callDerived($method,$params){
call_user_func_array(array($this,$method),$params);
}
}
class Derived extends Base{
function test($foo,$bar){
print "foo=$foo, bar=$bar\n";
}
}
$d = new Derived();
$d->callDerived('test',array('bar'=>'2','foo'=>1));
Outputs:
foo=2, bar=1
Which... is not exactly what I wanted - is there a way to achieve this beyond re-composing the array with the index order of func_get_args? And yes, of course, I could simply pass the whole array and deal with it in the function... but that's not what I want to do.
Thanks
No. PHP does not support named parameters. Only the order of parameters is taken into account. You could probably take the code itself apart using the ReflectionClass to inspect the function parameter names, but in the end you'd need to use this to reorder the array anyway.
The stock PHP class ReflectionMethod is your friend.
Example:
class MyClass {
function myFunc($param1, $param2, $param3='myDefault') {
print "test";
}
}
$refm = new ReflectionMethod('MyClass', 'myFunc');
foreach ($refm->getParameters() as $p)
print "$p\n";
And the result:
Parameter #0 [ <required> $param1 ]
Parameter #1 [ <required> $param2 ]
Parameter #2 [ <optional> $param3 = 'myDefault' ]
At this point you know the names of the parameters of the target function. With this information you can modify your method 'callDerived', and you can re-order the array to call_user_func_array according to the parameter names.
Good news, I had the same concern (I was looking for named arguments in PHP, like Python does), and found this useful tool : https://github.com/PHP-DI/Invoker
This uses the reflection API to feed a callable with some arguments from an array and also use optional arguments defaults for other parameters that are not defined in the array.
$invoker = new Invoker\Invoker;
$result = $invoker->call(array($object, 'method'), array(
"strName" => "Lorem",
"strValue" => "ipsum",
"readOnly" => true,
"size" => 55,
));
Have fun
UPDATE: PHP 8 Now supports named parameters. And it works with call_user_func_array if you pass an associative array. So you can simply do this:
<?php
function myFunc($foo, $bar) {
echo "foo=$foo, bar=$bar\n";
}
call_user_func_array('myFunc', ['bar' => 2, 'foo' => 1]);
// Outputs: foo=1, bar=2
In your code, you'll be happy to know that you don't have to change a thing. Just upgrade to PHP 8 and it'll work as you expected
You can simply pass an array and extract:
function add($arr){
extract($arr, EXTR_REFS);
return $one+$two;
}
$one = 1;
$two = 2;
echo add(compact('one', 'two')); // 3
This will extract as references, so there is close to no overhead.
I use a bitmask instead of boolean parameters:
// Ingredients
define ('TOMATO', 0b0000001);
define ('CHEESE', 0b0000010);
define ('OREGANO', 0b0000100);
define ('MUSHROOMS', 0b0001000);
define ('SALAMI', 0b0010000);
define ('PEPERONI', 0b0100000);
define ('ONIONS', 0b1000000);
function pizza ($ingredients) {
$serving = 'Pizza with';
$serving .= ($ingredients&TOMATO)?' Tomato':'';
$serving .= ($ingredients&CHEESE)?' Cheese':'';
$serving .= ($ingredients&OREGANO)?' Oregano':'';
$serving .= ($ingredients&MUSHROOMS)?' Mushrooms':'';
$serving .= ($ingredients&SALAMI)?' Salami':'';
$serving .= ($ingredients&ONIONS)?' Onions':'';
return trim($serving)."\n" ;
}
// Now order your pizzas!
echo pizza(TOMATO | CHEESE | SALAMI);
echo pizza(ONIONS | TOMATO | MUSHROOMS | CHEESE); // "Params" are not positional
For those who still might stumble on the question (like I did), here is my approach:
since PHP 5.6 you can use ... as mentioned here:
In this case you could use something like this:
class Base{
function callDerived($method,...$params){
call_user_func_array(array($this,$method),$params);
}
}
class Derived extends Base{
function test(...$params){
foreach ($params as $arr) {
extract($arr);
}
print "foo=$foo, bar=$bar\n";
}
}
$d = new Derived();
$d->callDerived('test',array('bar'=>'2'),array('foo'=>1));
//print: foo=1, bar=2
There is a way to do it and is using arrays (the most easy way):
class Test{
public $a = false;
private $b = false;
public $c = false;
public $d = false;
public $e = false;
public function _factory(){
$args = func_get_args();
$args = $args[0];
$this->a = array_key_exists("a",$args) ? $args["a"] : 0;
$this->b = array_key_exists("b",$args) ? $args["b"] : 0;
$this->c = array_key_exists("c",$args) ? $args["c"] : 0;
$this->d = array_key_exists("d",$args) ? $args["d"] : 0;
$this->e = array_key_exists("e",$args) ? $args["e"] : 0;
}
public function show(){
var_dump($this);
}
}
$test = new Test();
$args["c"]=999;
$test->_factory($args);
$test->show();
a full explanation can be found in my blog:
http://www.tbogard.com/2013/03/07/passing-named-arguments-to-a-function-in-php/

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

Categories