The title might be a bit confusing, but w/e.
Is it possible to do something like this?
define('test_1', 'test1');
define('test_2', 'test2');
define('test_3', 'test3');
$test='2';
echo test_$test;
I simply want to echo one of those defined constants (in this case 2) depending on what $test is, without using if() or switch().
You should be sorted with the following:
echo constant('test_'.$test);
Related
Is there any way at all to make a variable work like echo, as such:
$x = "echo";
$x "Hi there!";
If you understand what I mean? I've seen it done before only the variable was "system" and the code was
//taking $x = "system"
$x(blablabla);
Any ideas?
From the notes on echo's manual page:
Note: Because this is a language construct and not a function, it cannot be called using variable functions.
If you insist, you could say like eval "$x \"stuff\";";, but other than that or creating a function and using it instead, you're kinda out of luck.
You mean like this:
$x = 'printf';
$x('Hi there');
?
echo is a language construct, not a function, so it won't work
I have a very simple question. But is really making me crazy.
I have a statement say:
example and example with one php variable like $loggedin_user_name
First of all, I want to store the above sentence in MySQL database and then take it back whenever I want to print the above statement. It seems that their is no issue.
But when I tried to print data after extracting from database it is printing the same statement. But i guess, it has to print the logged in user name instead of $loggedin_user_name in the above statement.
So, is it possible to print the variable within the variable? If yes, please suggest a way.
use sprintf()
$str = "example and example with one php variable like %s";
Then load it from database and fill
$out = sprintf($str, $loggedin_user_name);
If it is always the same variable name, I would suggest using
echo str_replace($fromDb, '$variableToReplace', $variableToReplace);
You can use preg_match to find you variable name in string and then replace it with str_replace.
$name = "ABC";
$bla = "$name";
echo $bla; //ABC
Will always be "ABC", because PHP is evaluating your variable when asigning to $bla.
You can use single-quotes to avoid that behaviour (like $bla='$name'; //$name) or you quote the $-sign (like $bla="\$name"; //$name). Then you can store your string like you wanted into your database.
But you can not (only when using eval(), wich you MUST NOT DO in good PHP-Code) build this behaviour, that php has, when printing fulltext.
Like Mentioned in another answer, you should use printf or sprintf and replace the $loggedin_user_name with %s (for "string).
Best would be to concatinate a string:
$exampleWithUsername = 'example' . $loggedin_user_name;
echo $exampleWithUsername;
'example' is a hardcoded string, but you can give it a variable containing string $example, or directly concatinate $username into $example.
You can use eval function, it can be used like your example:
$loggedin_user_name = 'bilal';
$str = "example and example with one php variable like $loggedin_user_name";
eval("\$str = \"$str\";");
echo $str;
Cons:
If your str variable or string/code which you give to eval as a parameter is filled by users, this usage creates a vulnerability.
In case of a fatal error in the evaluated code, the whole script exits.
Earlier today I tried to do this:
Example 1:
<?php
echo $myVar || "rawr";
?>
I thought this might print out $myVar if it was set, and print "rawr" if not.
It printed a 1, I assume this is the result of the OR test.
What I then tried was this:
Example 2:
<?php
if ($myVar)
{
echo $myVar;
}
else
{
echo "rawr";
}
?>
Which is what I was trying to accomplish.
I think I understand why the first prints the results of the OR test rather than one of the variables, and also why I tried it - been spending some time on the bash shell recently :)
Can anyone tell me if there is a way to perform the text in example #2 but in similar syntax to example #1?
PHP 5.3:
echo $myVar ?: 'rawr';
Pre 5.3:
echo $myVar ? $myVar : 'rawr';
If $myVar may not be set you'd have to use isset($myVar) and $myVar as the condition (which then wouldn't work with the shorthand ?: syntax, as this would echo 1 if it was set, rather than the value).
echo (isset($myVar) and $myVar) ? $myVar : 'rawr';
PHP is notoriously inelegant in this department, and there really is no good way of making this test.
As a general solution, you 'd need to use the ternary operator as in empty($var) ? "rawr" : $var. However, in practice what happens is that you have one of two scenarios:
1. Your own variable
In this case where you define the variable yourself, the best solution is to just give it a known default value at the place you define it (possibly with the ternary operator).
2. Inside an array
If the array is one that should not be touched like one of the superglobals, then you can wrap the test inside a function (pretty much that's what everyone does).
If the array is one under your jurisdiction but it comes from an external source, you can use the "add the defaults" trick:
$incoming = array(...);
$defaults = array("foo" => "bar");
// Inject the defaults into $incoming without overwriting existing values
$incoming += $defaults;
At this point you know for a fact that every key inside $defaults also exists inside $incoming.
In PHP 5.3+ it is possible to leave out the second argument:
echo $myVar ?: 'rawr';
This is probably closest to what you want.
Try this:
echo $myVar = ($myVar) ? $myVar : 'rawr';
or
echo $myVar ? $myVar : 'rawr';
I think you want to use something like var_dump($varname) or isset($varname) ?
it's matter of operator precedence. you can't do that.
two points as a food for thought
if $myVar is not set, you'll get an error message, not "wawr";
by the time you're going to echo some variables, every one of them should be defined and have value. That will make your template clean and readable.
Try
echo ($myVar != null ? $myVar : "Rawr!");
I understand that wanting to update or remove a constant is the exact opposite if what it is meant for, but here is my problem.
I want to be able to format a value in same same fashion that a constant does. i.e.: echo foo;
Where it can just be plain text, instead of echoing a variable like $foo.
It may seem like a silly thing to want to do, but I am hoping to create use out of it. However, if this is not possible, I guess that is that.
PS. I 'would' just define it as a constant, however I want it to be able to update (like re-defining it during a foreach).
Sort of. The first one must be case-insensitive:
define("myConstant", "blah", true);
print myConstant; // blah
define("myConstant", "xxxx"); // No warning outputted
print myConstant; // xxxx
But, DON'T DO THIS! The whole point of a constant is that it's constant. Although you seem to sort of recognize this, what is wrong with that extra $ sign, really, versus a much more clear code style?
According to http://www.php.net/manual/en/function.define.php#92327, you can redefine constants on the fly if necessary.
define("FIRST_CONSTANT", 'my 1st value', true);
echo FIRST_CONSTANT;
// my 1st value
define('FIRST_CONSTANT', 'my 2nd value');
echo FIRST_CONSTANT;
// my 2nd value
You could use the name of a function like this:
<?php
function hello(){ return "bla"; }
$a = hello;
$b = $a();
echo $b;
?>
The title is in the question (EDIT: :P I mean the question is in the title), basically can I call variable $x before defining it further down the page?
Short answer, no.
Long answer, noooooooooooooooooooooooooooooooooooooooooo.
But seriously, you can refer to it, it just won't do what you want.
Depending on how strict your warnings on you can call an undeclared variable as much as you want. However until you assign it a value it won't have a value.
I am not quite sure to understand your point but if you want to write
echo $x;
$x = "2";
you will not get "2" as a result.
PHP will usually not issue a warning when you reference a variable that has not yet been assigned a value. PHP will create it on the fly and assign it the null value which will then be casted to whatever scope you have. For example
$a = $b + 5;
echo $a;
will print 5 because in this case $b will be interpreted as beeing 0.
I hope this will help
Jerome
No, the execution goes down the file. You can use a function though, to call later on once the variable has been defined. For example:
<?php
function meow() {
echo $kitty_noise;
}
?>
And then later on down the file...
<?php
$kitty_noice = 'meowwwwww!';
meow();
?>
Horrible example....