I know you can do: $hash('foo') and $$foo and also $bar[$foo], what are each of these things called?
$hash('foo') is a variable function.
$hash may contain a string with the function name, or an anonymous function.
$hash = 'md5';
// This means echo md5('foo');
// Output: acbd18db4cc2f85cedef654fccc4a4d8
echo $hash('foo');
$$foo is a variable variable.
$foo may contain a string with the variable name.
$foo = 'bar';
$bar = 'baz';
// This means echo $bar;
// Output: baz
echo $$foo;
$bar[$foo] is a variable array key.
$foo may contain anything that can be used as an array key, like a numeric index or an associative name.
$bar = array('first' => 'A', 'second' => 'B', 'third' => 'C');
$foo = 'first';
// This tells PHP to look for the value of key 'first'
// Output: A
echo $bar[$foo];
The PHP manual has an article on variable variables, and an article on anonymous functions (but I didn't show an example above for the latter).
Related
This question already has answers here:
Are PHP Variables passed by value or by reference?
(16 answers)
Closed 1 year ago.
Here's the code
class Foo {
public $a;
}
$arr = [];
$foo = new Foo();
$foo->a = 1;
$arr[0] = $foo;
$arr[0]->a = 2;
echo $foo->a;
The result is 2 in my testing. However I am not sure whether this behavior is guaranteed or the behavior is random and/or will change based on the state of optimizer/version/memory usage/associative or not/...
Is it guaranteed?
Note: the reason I am having this question is the following code will output 1
$arr = [];
$foo = 1;
$arr[0] = $foo;
$arr[0] = 2;
echo $foo;
As those $foo and $arr are pointing to the same position at memory, so any changing from $arr will affect at $foo too.
in fact :
$arr[0] === $foo
if you want to clone a var from $foo you must test this:
$arr[0] = clone $foo;
so any modification in $arr wont affect at $foo and vice versa.
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"
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.
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]
For example:
$array = array('f', 'b');
assign($foo, $bar, $array);
// now $foo = 'f' and $bar = 'b'
Does something like this exist in the PHP language? I have never needed something like this before and cannot find anything that will do this.
I just wanted to make sure before I write the function myself - I don't want to write something that already exists within the language.
list ($foo, $bar) = $array;
list() is something like the opposite of array() and its a language construct. Its especially important to know, that even if its listed in the functions reference of the manual (list()), it isn't, because no function is writeable.
Pretty close to PHP's extract() function.
You need to specify the var name as they key for each value in the array though.
$array = array('foo' => 'f', 'bar' => 'b');
extract($array);
// now $foo = 'f' and $bar = 'b'
you can use php's list() function
$array = array('f', 'b');
list($foo, $bar) = $array;
now it is
$foo = 'f' and $bar = 'b';
php.net/list