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

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

Related

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 5.4 Anonymous Function in Array undefine

This is PHP 5.4 code...
<?php
function abc($YesNo){return $YesNo["value"];}
$YesNo = array("value"=>"No","text"=>"No");
$x = array("active"=>function(){return abc($YesNo);});
echo $x['active']();
?>
Notice: Undefined variable: YesNo on line 7
Output Should be : Yes
if i directly put array in code by replace $YesNo like
<?php
function abc($YesNo){return $YesNo["value"];}
$x = array("active"=>function(){return abc(array("value"=>"Yes","text"=>"Yes"));});
echo $x['active']();
?>
output : Yes
which is correct output. Now what's the problem in first code. I need that for re-usability
Try this,
You can use use for passing data to a closure.
<?php
function abc($YesNo){return $YesNo["value"];}
$YesNo = array("value"=>"No","text"=>"No");
$x = array("active"=>function() use ($YesNo) {return abc($YesNo);});
echo $x['active']();
?>
You provide your anonymous function with a parameter:
$x = array("active"=>function($param){return abc($param);});
then you call it:
echo $x['active']($YesNo);
You may use the use keyword to make your function aware of an external variable:
$x = array("active"=>function() use ($YesNo) {return abc($YesNo);});
but it would be quite against the idea of reusability, in this case.
The problem is that your variable is not accessible within the function due to Variable Scope.
Because the array is defined outside of the function, it is not by default available inside the function.
There's a couple of solutions
Disclaimer: These are intended to fit within the scope of the question. I understand that they are not necessarily best practice, which would require a larger discussion
First Option:
You can declare the array within the function, like below. This is useful if you don't need access to it outside of the function.
function abc($YesNo){
$YesNo = array("value"=>"No","text"=>"No");
return $YesNo["value"];
}
Second Option:
Within your abc function, you can add the line global $YesNo. This is useful if you do need access to the array outside of the function:
function abc($YesNo){
global $YesNo;
return $YesNo["value"];
}
Other options exist (such as moonwave99's answer).
Finally:
Why are you putting an anonymous function within the array of $x? Seems like a path that will lead to problems down the road....
Your variable $YesNo needs to be visible in the scope of your anonymous function. You need to add global $YesNo as the first statement in that function:
So
$x = array("active"=>function(){return abc($YesNo);});
becomes
$x = array("active"=>function(){global $YesNo; return abc($YesNo);});
... also "value"=>"No" should be "value"=>"Yes" if you want it to return "Yes"

How to access a class const dynamically in 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.

if i define something in a class, how do i call in within the class?

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__;

Categories