I have encountered the need to access/change a variable as such:
$this->{$var}
The context is with CI datamapper get rules. I can't seem to find what this syntax actually does. What do the {'s do in this context?
Why can't you just use:
$this->var
This is a variable variable, such that you will end up with $this->{value-of-$val}.
See: http://php.net/manual/en/language.variables.variable.php
So for example:
$this->a = "hello";
$this->b = "hi";
$this->val = "howdy";
$val = "a";
echo $this->{$val}; // outputs "hello"
$val = "b";
echo $this->{$val}; // outputs "hi"
echo $this->val; // outputs "howdy"
echo $this->{"val"}; // also outputs "howdy"
Working example: http://3v4l.org/QNds9
This of course is working within a class context. You can use variable variables in a local context just as easily like this:
$a = "hello";
$b = "hi";
$val = "a";
echo $$val; // outputs "hello"
$val = "b";
echo $$val; // outputs "hi"
Working example: http://3v4l.org/n16sk
First of all $this->{$var} and $this->var are two very different things. The latter will request the var class variable while the other will request the name of the variable contained in the string of $var. If $var is the string 'foo' then it will request $this->foo and so on.
This is useful for dynamic programming (when you know the name of the variable only at runtime). But the classic {} notation in a string context is very powerful especially when you have weird variable names:
${'y - x'} = 'Ok';
$var = 'y - x';
echo ${$var};
will print Ok even if the variable name y - x isn't valid because of the spaces and the - character.
Related
Say I had the variable $foo which has a value of "bar" and I wanted to make a variable variable from it, but also append the string "123" to it, so that the variable name is $bar123. How would I do this?
I already know that $$foo = "abc123" would make a variable $bar with the value of "abc123", but I don't know how to append a string to this variable name.
Using variable variables, you can do something as the following:
<?php
$a = "foo";
$number = 123;
$b = $a . "$number";
$$b = "Hello World!";
echo ${$b};
However, as #smith said, it is better to use associative arrays here.
I realised the solution was fairly simple:
$foo = "bar";
$x = $foo . "123"
$$x = "random important variable value"
This is my case.(i changed my case)
I have variable let say $var1 from database and method test($var1)
$var1 = getFromDatabase();
//now $var1 contaion "This is new variable".$var2
Then in test method i will do simple string operation from the $var1 equation.
test($var1){
$var2 = "variable 2";
//I want to extract $var1 so that string will be combined
$value = $var1;
$value_expected = "This is new variable".$var2;
}
But $value will contain "This is new variable".$var2.
I expect $value contain This is new variable variable 2 from the $var1 equation.
Is there any solution? Is that possible to do?
Thank You.
Don't use quotes. $var1 = $var2 + $var3;
Quotes mean you're working with strings
Apart from that, you can't access local variables like that. Variables declared inside the function will not be accessible outside of it. And even if you could you would still not be getting what you expect because you're using $var2 and $var3 before initializing them.
What you're looking for is possible by passing functions around. For example:
function test( $var1 ) {
$var2 = 4;
$var3 = 5;
// this line calls the function named in $var1 with $var2 and $var3 as arguments
$value = call_user_func( $var1, $var2, $var3 );
// in later versions of PHP you can do this instead:
// $value = $var1( $var2, $var3 );
}
function addThem( $a, $b ) {
return $a + $b;
}
test( 'addThem' );
Notice that the method of combining variables is passed as a function (or at least, the closest PHP has to passing functions around; PHP is an odd language). Also the values it works on must be passed as parameters.
I have got a variable called $Title
It is possible that the variable contains a string,
example A: 'Foo'
But the variable can also contain a reference to an different variable,
example B: '$Foo'
When I use print $Title php returns 'Foo' (EX A) or '$Foo' (EX B) as an string.
When I use print $$Title php tries to return the value of a variable named $Foo (EX A) or $$Foo (EX B)
I want to accomplish the following:
When $Title contains just a string, print that string
When $Title contains the reference to a variable, look up that variable and show its content
I could just look for the first character in the string. When it is $ use echo $$Title ELSE use echo $Title, but it is possible that $Title contains something like this:
$Title = '$Foo . \'Bar\' . $Bar . \'Foo\'';
In that case $Foo and $Bar are variables and need to act as such, 'Bar' and 'Foo' are strings and need to act as such.
How can I make this able to work??
A string is always just a string. A string is never a variable.
Case 1, a plain string:
$foo = 'bar';
echo $foo; // bar
echo $$foo; // content of $bar if it exists
Case 2, a "variable in a string":
$foo = 'bar';
$bar = "$foo"; // $bar is now the string 'bar', the variable is interpolated immediately
echo $bar; // bar
echo $$bar; // bar (content of $bar)
Case 3, a string with a dollar in it:
$foo = '$bar';
echo $foo; // $bar
echo $$foo; // invalid variable name "$bar"
$$foo resolves to the variable name $$bar, which is an invalid name.
You cannot have "variables in strings". Writing "$foo" immediately interpolates the value of $foo and gives you back a new string.
Just maybe, you want this:
$foo = 'bar'; // the string "bar"
$baz = '$foo'; // the string "$foo"
// MAGIC
echo $baz; // echoes "bar"
I.e., if your string contains a dollar followed by the name of a variable, you want to substitute that value. First I'd say this is a bad idea. Then I'd say you will have to extract all those "dollar strings" out of your string, check if the variable exists, then replace the value in the string using normal string manipulation. Yes, you could do it using eval, but no, that's not a good idea. For the above code, something like this'll do:
if ($baz[0] == '$') {
$varName = substr($baz, 1);
if (isset($$varName)) {
$baz = $$varName;
}
}
The is_string PHP function is used to check if a value is a string. This could be used within an if () statement to treat strings in one way and non-strings in another. It will return true or false.
<?php
if (is_string(23))
{
echo "Yes";
} else {
echo "No";
}
?>
The code above should output "No" because 23 is not a string. Let's try this again:
<?php
if (is_string("Hello World"))
{
echo "Yes";
} else {
echo "No";
}
?>
Since "Hello World" is a string, this would echo "Yes".
Use a if statement to check if the $variable is a string..
if(is_string($var)) {
echo $var;
} else {
// What do you want to achieve here?
}
Code like this:
$Title = '$Foo . \'Bar\' . $Bar . \'Foo\'';
can't be evaluated when you try to print it, it's evaluated at the moment of assignment. The reason variable names are not being replaced by their values in your case are single quotes.
$a = 1;
$b = 2;
$var = '$a + $b'; // this is a string
echo $var; // $a + $b
$var = "$a + $b"; // this is also a string, but variables will be processed
echo $var; // 1 + 2
Note, that in second scenario it only processes the variable names, it doesn't run the code ('+' is a string, not an operation).
If you want to keep the '$a + $b' as a string within your $title and evaluate it as a PHP code at the moment, when you print it, you need to use eval function. However, I strongly suggest trying to avoid using this function as much as possible.
As I can understand, string may be just string or some sort of variable 'reference'.
Will this work for you or there is always $ if variable reference?
$var1='test';
$ref1='var1';
if(isset($$ref1)) {
// variable exists
}
else {
// no such variable
}
You can use the dangerous eval php contruct. But be warned if any of the string is coming from a user input
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
This is just a copy and paste from (PHP eval documentation)[http://php.net/manual/en/function.eval.php]
Hello I am new to PHP and I don't know exactaly what does this code means
$de = array('Ä'=>'ae','ä'=>'ae','Ü'=>'ue','ü'=>'ue', 'Ö'=>'oe', 'ö'=>'oe', 'ß'=>'ss');
strtr($str, ${$de});
The only thing that I need to know is what does ${$de} mean?
It's a variable variable, one of the most intriguing part of the php implementation.
Sometimes usefull, always confusing:
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";
$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a
$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World
....
That's a variable variable.
http://php.net/manual/en/language.variables.variable.php
Known as Variables Variable
http://php.net/manual/en/language.variables.variable.php
I've written and played around with alot of PHP function and variables where the original author has written the original code and I've had to continue on developing the product ie. Joomla Components/Modules/Plugins and I've always come up with this question:
How does the '&' symbol attached to a function or a variable affect the outcome?
For instance:
$variable1 =& $variable2;
OR
function &usethisfunction() {
}
OR
function usethisfunction(&thisvariable) {
{
I've tried searching through the PHP manual and other related sources but cannot find anything that specifically addresses my question.
These are known as references.
Here is an example of some "regular" PHP code:
function alterMe($var) {
$var = 'hello';
}
$test = 'hi';
alterMe($test);
print $test; // prints hi
$a = 'hi';
$b = $a;
$a = 'hello';
print $b; // prints hi
And this is what you can achieve using references:
function alterMe(&$var) {
$var = 'hello';
}
$test = 'hi';
alterMe($test);
print $test; // prints hello
$a = 'hi';
$b &= $a;
$a = 'hello';
print $b; // prints hello
The nitty gritty details are in the documentation. Essentially, however:
References in PHP are a means to access the same variable content by different names. They are not like C pointers; instead, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The closest analogy is with Unix filenames and files - variable names are directory entries, while variable content is the file itself. References can be likened to hardlinking in Unix filesystem.
<?php
$a = "hello"; # $a points to a slot in memory that stores "hello"
$b = $a; # $b holds what $a holds
$a = "world";
echo $b; # prints "hello"
Now if we add &
$a = "hello"; # $a points to a slot in memory that stores "hello"
$b = &$a; # $b points to the same address in memory as $a
$a = "world";
# prints "world" because it points to the same address in memory as $a.
# Basically it's 2 different variables pointing to the same address in memory
echo $b;
?>
It is a reference. It allows 2 variable names to point to the same content.