PHP variable in a string - php

I have this tiny code:
$a = "apple";
$var = "I like the $a";
echo $var;
echo "<br>";
$a = "pear";
echo $var;
OUTPUT:
I like the apple
I like the apple
OUTPUT I NEED:
I like the apple
I like the pear
Anyone knows how can I update the var in the string dynamically?
Thanks

Your $var string is parsed at the moment the interpreter reaches it, so changing your $a variable won't replace its value. There are many options to accomplish what you are trying to do alternatively.
You can store your string format in $var and then apply sprintf:
$var = 'I like the %s';
echo sprintf($var, 'apple');
echo sprintf($var, 'pear');
Or you could just create a function that receives what you like as a parameter:
function generateLikeString($what) {
return "I like the $what";
}
echo generateLikeString('apple');
echo generateLikeString('pear');

You are editing the value of $a after you have used it in $var. It will not affect $var if you change $a afterwards. You have to do this again:
$a = "pear";
$var = "I like the $a";
Or do this:
$a = "apple";
$var = "I like the ";
echo $var . $a;
echo "<br>";
$a = "pear";
echo $var . $a;

Related

What is the difference between $message and $$message in php? [duplicate]

Example is a variable declaration within a function:
global $$link;
What does $$ mean?
A syntax such as $$variable is called Variable Variable.
For example, if you consider this portion of code:
$real_variable = 'test';
$name = 'real_variable';
echo $$name;
You will get the following output:
test
Here:
$real_variable contains 'test'
$name contains the name of your variable: 'real_variable'
$$name mean "the variable thas has its name contained in $name"
Which is $real_variable
And has the value 'test'
EDIT after #Jhonny's comment:
Doing a $$$?
Well, the best way to know is to try ;-)
So, let's try this portion of code:
$real_variable = 'test';
$name = 'real_variable';
$name_of_name = 'name';
echo $name_of_name . '<br />';
echo $$name_of_name . '<br />';
echo $$$name_of_name . '<br />';
And here's the output I get:
name
real_variable
test
So, I would say that, yes, you can do $$$ ;-)
The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So, consider this example
$inner = "foo";
$outer = "inner";
The variable:
$$outer
would equal the string "foo"
It's a variable's variable.
<?php
$a = 'hello';
$$a = 'world'; // now makes $hello a variable that holds 'world'
echo "$a ${$a}"; // "hello world"
echo "$a $hello"; // "hello world"
?>
It creates a dynamic variable name. E.g.
$link = 'foo';
$$link = 'bar'; // -> $foo = 'bar'
echo $foo;
// prints 'bar'
(also known as variable variable)
I do not want to repeat after others but there is a risk using $$ :)
$a = '1';
$$a = 2; // $1 = 2 :)
So use it with head. :)
It evaluates the contents of one variable as the name of another. Basically it gives you the variable whose name is stored in $link.
this worked for me (enclose in square brackets):
$aInputsAlias = [
'convocatoria' => 'even_id',
'plan' => 'acev_id',
'gasto_elegible' => 'nivel1',
'rubro' => 'nivel2',
'grupo' => 'nivel3',
];
/* Manejo de los filtros */
foreach(array_keys($aInputsAlias) as $field)
{
$key = $aInputsAlias[$field];
${$aInputsAlias[$field]} = $this->request->query($field) ? $this->request->query($field) : NULL;
}

How do re-parse a variable string that contains a variable name?

$a = 'i am a $b'; // declared before $b is declared
function x(....) {
global $a;
$b = 'boy';
$c = '{$a}'; // i know this doesn't work. how can I make it work?
}
I want $c to return "i am a boy"
This is a simple example of my issue. In the real case, there are many variables involved. Is there a simple fix?
This is where functions come in handy. They take in the parameters and return some compiled value.
// create named function
function namedFn($b) {
return "i am a $b";
}
// or anonymous
$f = function ($b) {return "i am a $b"; };
// call function and pass $b as argument
$b = 'boy';
echo namedFn($b);
echo $f($b);
If you really need to reparse some string with the contents of your variables, just use str_ireplace
$a = 'i am a $b';
echo str_ireplace('$b', $b, $a); // $search , $replace , $subject

In PHP, what's the diff : $var2=$var1 ; $var2=&$var1; [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Reference assignment operator in php =&
$var2 = $var1;
$var2 = &$var1;
Example:
$GLOBALS['a']=1;
function test()
{
global $a;
$local=2;
$a=&$local;
}
test();
echo $a;
Why is $a still 1 ?
The operator =& works with references and not values.
The difference between $var2=$var1 and $var2=&$var1 is visible in this case :
$var1 = 1;
$var2 = $var1;
$var1 = 2;
echo $var1 . " " . $var2; // Prints '2 1'
$var1 = 1;
$var2 =& $var1;
$var1 = 2;
echo $var1 . " " . $var2; // Prints '2 2'
When you use the =& operator you don't say to $var2 "take the value of $var1 now" instead you say something like "Your value will be stored at the exact same place that the value of $var1".
So anytime you change the content of $var1 or $var2, you will see the modification in the two variables.
For more informations look on PHP.net
EDIT :
For the global part, you'll need to use $GLOBALS["a"] =& $local; Cf. documentation.
When you do $var2 = $var1, PHP creates a copy of $var1, and places it in $var2. However, if you do $var2 = &$var1, no copy is made. Instead, PHP makes $var2 point at $var1 - what this means is that you end up with two variables that point at the exact same thing.
An example:
$var1 = "Foo";
$var2 = $var1; // NORMAL assignment - $var1's value is copied into $var2
$var3 = &$var1; // NOT normal copy!
echo $var2; // Prints "Foo".
echo $var3; // Also prints "Foo".
$var1 = "Bar"; // Change $var1.
echo $var2; // Prints "Foo" as before.
echo $var3; // Now prints "Bar"!
global $a;
This is equivalent to:
$a = &$GLOBALS['a'];
When you assign $a a new reference, you're changing $a and not $GLOBALS['a'].
What do you expect to be output below?
$GLOBALS['a']=1;
function test()
{
$a='foobar'; // $a is a normal variable
$a=&$GLOBALS['a']; // same as: global $a;
$local=2;
$a=&$local;
}
test();
echo $a;

Variable variables in OOP

I'm having a little struggle on this one and would appreciate some help.
In PHP variable variables can easily be defined like this
$a = "myVar";
$$a = "some Text";
print $myVar; //you get "some Text"
Now, how do I do that in a OOP enviroment? I tried this:
$a = "myVar";
$myObject->$a = "some Text"; //I must be doing something wrong here
print $myObject->myVar; //because this is not working as expected
I also tried $myObject->{$a} = "some Text" but it's not working either. So I must be very mistaken somewhere.
Thanks for any help!
This works for me:
class foo {
var $myvar = 'stackover';
}
$a = 'myvar';
$myObject = new foo();
$myObject->$a .= 'flow';
echo $myObject->$a; // prints stackoverflow
This should work
class foo {
var $myvar = 'stackover';
}
$a = 'myvar';
$myObject = new foo();
$myObject->$a = 'some text';
echo $myObject->myvar;

Is there a way to bind variables? PHP 5

Using PHP 5 I would like to know if it is possible for a variable to dynamically reference the value
of multiple variables?
For example
<?php
$var = "hello";
$var2 = " earth";
$var3 = $var.$var2 ;
echo $var3; // hello earth
Now if I change either $var or $var2 I would like $var3 to be updated too.
$var2 =" world";
echo $var3;
This still prints hello earth, but I would like to print "hello world" now :(
Is there any way to achieve this?
No, there is no way to do this in PHP with simple variables. If you wanted to do something like this in PHP, what you'd probably do would be to create a class with member variables for var1 and var2, and then have a method that would give you a calculated value for var3.
This should do the trick. I tested it on PHP 5.3 and it worked. Should also work on any 5.2.x version.
You could easily extend this with an "add"-Method to allow an arbitrary number of strings to be placed in the object.
<?php
class MagicString {
private $references = array();
public function __construct(&$var1, &$var2)
{
$this->references[] = &$var1;
$this->references[] = &$var2;
}
public function __toString()
{
$str = '';
foreach ($this->references as $ref) {
$str .= $ref;
}
return $str;
}
}
$var1 = 'Hello ';
$var2 = 'Earth';
$magic = new MagicString($var1, $var2);
echo "$magic\n"; //puts out 'Hello Earth'
$var2 = 'World';
echo "$magic\n"; //puts out 'Hello World'
No. Cannot be done without utilizing some sort of custom String class.
Check the PHP manual for types and variables, especially this passage:
By default, variables are always
assigned by value. That is to say,
when you assign an expression to a
variable, the entire value of the
original expression is copied into the
destination variable. This means, for
instance, that after assigning one
variable's value to another, changing
one of those variables will have no
effect on the other. For more
information on this kind of
assignment, see the chapter on
Expressions.
it's a bit late, but it's interesting question.
You could do it this way:
$var = "hello";
$var2 = " earth";
$var3 = &$var;
$var4 = &$var2;
echo $var3.$var4; // hello earth
From my point of view the following code is a little closer to the required:
$a = 'a';
$b = 'b';
$c = function() use (&$a, &$b) { return $a.$b; };
echo $c(); // ab
$b = 'c';
echo $c(); // ac
Create a function.
function foobar($1, $2){
$3 = "$1 $2";
return $3;
}
echo foobar("hello", "earth");
echo foobar("goodbye", "jupiter");

Categories