I'm trying to convert a PHP variable to a JS variable using a little helper function that uses variable variables. To simplify, here is what I'm trying to accomplish:
$project_key = 'project 1';
function to_js($variable) {
echo $$variable;
}
to_js('$project_key');
this is supposed simply print
project 1
instead i get
Undefined variable: $project_key
which tells me the variable is being targeted but can't be accessed from the function. How can I access the global var $project_key from within the function if supplied only with the string $project_key?
Omit the leading $ from $project_key in the following line:
to_js('$project_key');
It should be:
to_js('project_key');
The $ in a variable is not part of the variables name, so you don't need to include it when referencing it in a variable variable.
Remove first $ sign before $variable. If you use $$ the project 1 will be considered as a variable but that is not defined as a variable.
$project_key = 'project 1';
function to_js($variable) {
echo $variable;
}
to_js($project_key);
Reference of $$
Try echoing your variable with script tags around it.
echo "<script>var x =" . $variable . "</script>";
$variable - being the variable you have stored in php
x - being the variable you want to be stored in Javascript.
Try removing the quotes in:
to_js('$project_key');
To be to_js($project_key); as if you use it as to_js('$project_key'); then you set the $variable in the function to the text: '$project_key'.
Wrong answer!#mehedi-pstu2k9 answer's is correct
Reference of $$
See:
https://stackoverflow.com/a/4169891/4977144
Related
I created a function to check for special characters in a string, but I can't seem to get it to echo the response message
Here is my code
<?php
function chk_string($string){
if (preg_match('/[\^£$%&*()}{##~?><>|=_+¬-]/', $string))
{
$chk_str="false";
} else {
$chk_str="true";
}
return $chk_str;
}
$string="this is just a test" ;
chk_string($string) ;
echo $chk_str;
?>
The "echo $chk_str" is not echoing anything.
If you did
$chk_str = chk_string($string);
then you could echo $chk_str;.
The $chk_str you are trying to echo is only visible in your function.
More description:
Your function (chk_string) is in a different scope than your echo.
Your function returns a variable, but that variable is "lost", since you don't assign it to another variable.
Your code currently does something like this line by line:
Your function declaration
$string means "this is just a test"
your functions result as a string, just floating in the code
write out a variable that doesn't exist.
I hope this helped in someway.
You need to store returned value in a particular variable if you want to echo that variable like this,
$chk_str = chk_string($string) ;
echo $chk_str;
Another way you can just directly echo returned value like this,
echo chk_string($string) ;
Your question is about variable scope and it is answered already, but I would recommend you to take a look at variable scope here https://www.php.net/manual/en/language.variables.scope.php.
Basically, every variable has its scope and we can not access a variable outside its scope. In your case, scope of variable $chk_str is inside function chk_string so you can not access it outside of the function. Because you return value of $chk_str in function chk_string so you still can access its value through response of function chk_string, for example:
echo chk_string('a string');
OR
$result = chk_string('a string');
echo $result;
I am trying to check defined variables based on passing a single portion of the variable. (The rest of the variable is static and all other portions of it are the same), so I made a test to find out if this is possible.
It does not work, but perhaps I am doing something small that is easily fixed.
define('TEST', 'works');
$test = 't';
echo TES . strtoupper($test);
echo eval('TES . strtoupper('.$test.');');
echo eval('TES . strtoupper(\'$test\');');
echo eval('TES' . strtoupper($test) . ';');
If you want to check if a constant is defined, simply use defined()
<?php
if (defined('TEST')) {
echo TEST;
}
?>
This should work for you:
Just use constant() to build the constant name as string and then pass it to the function.
echo constant("TES". strtoupper($test));
output:
works
'TEST' is not a global variable. It is a constant. The constants have global scope, they can be accessed from any context (given you know the name of the constant you want to use). There is no need to do any hack using eval().
If you generate the name of the constant on runtime for some reason, you can use the PHP function defined() to check if there is a constant already defined having that name and, if the constant exists, you can get its value using the function constant()
Like this:
define('TEST', 'works');
$test = 't';
echo 'TES'.strtoupper($test);
// Compute the constant's name
$name = 'TES'.strtoupper($test);
// Check if the constant exists and get its value
if (defined($name)) {
echo("The constant '".$name."' is already defined.\n");
echo("It's value is: ".constant($name)."\n");
}
This works with simple variables. But it shows empty result with complex variables. AM I MISSING SOMETHING HERE? or is there anyother way around. Thanks.
#1. This works with simple variables.
$object = "fruit";
$fruit = "banana";
echo $$object; // <------------ WORKS :outputs "banana".
echo "\n";
echo ${"fruit"}; // <------------ This outputs "banana".
#2. With complex structure it doesn't. am I missing something here?
echo "\n";
$result = array("node"=> (object)array("id"=>10, "home"=>"earth", ), "count"=>10, "and_so_on"=>true, );
#var_dump($result);
$path = "result['node']->id";
echo "\n";
echo $$path; // <---------- This outputs to blank. Should output "10".
Not exactly using variable variables, but if you want to use a variable as the var name, eval should work
$path = "result['node']->id";
eval("echo $".$path.";");
From php.net's page on variable variables
A variable variable takes the value of a variable and treats that as the name of a variable.
The issue is that result['node']->id is not a variable. result is the variable. If you turn on error reporting for PHP notices you will see the following in your output:
PHP Notice: Undefined variable: result['node']->id ...
This can be solved as follows:
$path = "result";
echo "\n";
echo ${$path}['node']->id;
The curly braces around $path are required.
In order to use variable variables with arrays, you have to resolve an
ambiguity problem. That is, if you write $$a[1] then the parser needs
to know if you meant to use $a[1] as a variable, or if you wanted $$a
as the variable and then the [1] index from that variable. The syntax
for resolving this ambiguity is: ${$a[1]} for the first case and
${$a}[1] for the second.
If not present the statement is equivalent to
${$path['node']->id}
which will result in the following output:
PHP Warning: Illegal string offset 'node' in /var/www/html/variable.php on line 18
PHP Notice: Undefined variable: r in /var/www/html/variable.php on line 18
PHP Notice: Trying to get property of non-object in /var/www/html/variable.php on line 18
I understand the usage of complex (curly) syntax within a string, but I don't understand it's purpose outside of a string.
I just found this code in CakePHP that I cannot understand:
// $class is a string containg a class name
${$class} =& new $class($settings);
If somebody could help me understand why is used here, and what is the difference between this and:
$class =& new $class($settings);
Thank you.
Easiest way to understand this is by example:
class FooBar { }
// This is an ordinary string.
$nameOfClass = "FooBar";
// Make a variable called (in this case) "FooBar", which is the
// value of the variable $nameOfClass.
${$nameOfClass} = new $nameOfClass();
if(isset($FooBar))
echo "A variable called FooBar exists and its class name is " . get_class($FooBar);
else
echo "No variable called FooBar exists.";
Using ${$something} or $$something. is referred to in PHP as a "variable variable".
So in this case, a new variable called $FooBar is created and the variable $nameOfClass is still just a string.
An example where the usage of the complex (curly) syntax outside of a string would be necessary is when forming a variable name out of an expression, consisting of more than just one variable. Consider the following code:
$first_name="John";
$last_name="Doe";
$array=['first','last'];
foreach ($array as $element) {
echo ${$element.'_name'}.' ';
}
In the code above the echo statement will output the value of the variable $first_name during the first loop, and the value of the variable $last_name during the second loop. If you were to remove the curly brackets the echo statement would try to output the value of the variable $first during the first loop and the value of the variable $last during the second loop. But since these variables were not defined the code would return an error.
The first example creates a dynamically named variable (name is the value of the class variable), the other overwrites the value of the class variable.
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);
}