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'));
Related
How can I get PHP to evaluate a static variable in double quotes?
I want to do something like this:
log("self::$CLASS $METHOD entering");
I've tried all sorts of {} combos to get the variable value of self::$CLASS, but nothing has worked. I've currently settled with string concatenation but it is a pain to type:
log(self::$CLASS . " $METHOD entering");
Sorry, you can't do that. It only works for simple expressions. See here.
Unfortunately there is no way how to do this yet. Example in one of answers here will not work, because {${self::$CLASS}} will not returns content of self::$CLASS, but will returns content of variable with name in self::$CLASS.
Here is an example, which does not returns myvar, but aaa:
$myvar = 'aaa';
self::$CLASS = 'myvar';
echo "{${self::$CLASS}}";
Use an anonymous identity function stored in a variable. This way you will have $ immediately after {:
$I = function($v) { return $v; };
$interpolated = "Doing {$I(self::FOO)} with {$I(self::BAR)}";
(I am using class constants in this example but this will work with static variables too).
I don’t know the answer to your question, but you can show the class name and method using the __METHOD__ magic constant.
<?php
class test {
public $static = 'text';
public $self = __CLASS__;
// static Method
static function author() {
return "Frank Glück";
}
// static variable
static $url = 'https://www.dozent.net';
public function dothis() {
$self = __CLASS__;
echo <<<TEST
{${!${''}=static::author()}} // works
{$self::author()} // works
{$this->self::author()} // works
${!${''}=self::author()} // works
{${$this->self}}::author()}} // don't works
${${self::author()}} // do/don't works but with notice
${#${self::author()}} // works but with # !
TEST;
}
}
$test = 'test'; // this is the trick, put the Classname into a variable
echo "{$test::author()} {$$test::$url}";
echo <<<HTML
<div>{$test::author()}</div>
<div>{$$test::$url}</div>
HTML;
$test = new test();
$test->dothis();
I know this is an old question but I find it odd that noone has suggested the [sprintf][1] function yet.
say:
<?php
class Foo {
public static $a = 'apple';
}
you would use it with:
echo sprintf( '$a value is %s', Foo::$a );
so on your example its:
log(
sprintf ( ' %s $METHOD entering', self::$CLASS )
);
//define below
function EXPR($v) { return $v; }
$E = EXPR;
//now you can use it in string
echo "hello - three is equal to $E(1+2)";
Just live with the concatenation. You'd be surprised how inefficient variable interpolation in strings can be.
And while this could fall under the umbrella of pre-optimization or micro-optimization, I just don't think you actually gain any elegance in this example.
Personally, if I'm gonna make a tiny optimization of one or the other, and my choices are "faster" and "easier to type" - I'm gonna choose "faster". Because you only type it a few times, but it's probably going to execute thousands of times.
Yes this can be done:
log("{${self::$CLASS}} $METHOD entering");
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
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
How can I get PHP to evaluate a static variable in double quotes?
I want to do something like this:
log("self::$CLASS $METHOD entering");
I've tried all sorts of {} combos to get the variable value of self::$CLASS, but nothing has worked. I've currently settled with string concatenation but it is a pain to type:
log(self::$CLASS . " $METHOD entering");
Sorry, you can't do that. It only works for simple expressions. See here.
Unfortunately there is no way how to do this yet. Example in one of answers here will not work, because {${self::$CLASS}} will not returns content of self::$CLASS, but will returns content of variable with name in self::$CLASS.
Here is an example, which does not returns myvar, but aaa:
$myvar = 'aaa';
self::$CLASS = 'myvar';
echo "{${self::$CLASS}}";
Use an anonymous identity function stored in a variable. This way you will have $ immediately after {:
$I = function($v) { return $v; };
$interpolated = "Doing {$I(self::FOO)} with {$I(self::BAR)}";
(I am using class constants in this example but this will work with static variables too).
I don’t know the answer to your question, but you can show the class name and method using the __METHOD__ magic constant.
<?php
class test {
public $static = 'text';
public $self = __CLASS__;
// static Method
static function author() {
return "Frank Glück";
}
// static variable
static $url = 'https://www.dozent.net';
public function dothis() {
$self = __CLASS__;
echo <<<TEST
{${!${''}=static::author()}} // works
{$self::author()} // works
{$this->self::author()} // works
${!${''}=self::author()} // works
{${$this->self}}::author()}} // don't works
${${self::author()}} // do/don't works but with notice
${#${self::author()}} // works but with # !
TEST;
}
}
$test = 'test'; // this is the trick, put the Classname into a variable
echo "{$test::author()} {$$test::$url}";
echo <<<HTML
<div>{$test::author()}</div>
<div>{$$test::$url}</div>
HTML;
$test = new test();
$test->dothis();
I know this is an old question but I find it odd that noone has suggested the [sprintf][1] function yet.
say:
<?php
class Foo {
public static $a = 'apple';
}
you would use it with:
echo sprintf( '$a value is %s', Foo::$a );
so on your example its:
log(
sprintf ( ' %s $METHOD entering', self::$CLASS )
);
//define below
function EXPR($v) { return $v; }
$E = EXPR;
//now you can use it in string
echo "hello - three is equal to $E(1+2)";
Just live with the concatenation. You'd be surprised how inefficient variable interpolation in strings can be.
And while this could fall under the umbrella of pre-optimization or micro-optimization, I just don't think you actually gain any elegance in this example.
Personally, if I'm gonna make a tiny optimization of one or the other, and my choices are "faster" and "easier to type" - I'm gonna choose "faster". Because you only type it a few times, but it's probably going to execute thousands of times.
Yes this can be done:
log("{${self::$CLASS}} $METHOD entering");
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 :-)