PHP object properties - php

I'm new to OOP in PHP and I find the difference between the following two expressions difficult to understand.
$object->$foo;
$object->foo;
Maybe it's my fault, but I could not find the relevant part in the manual.

The first call $obj->$foo is using a so called variable variable. Check this:
class A {
public $foo = 1;
}
$a = new A();
$foo = 'foo';
// now you can use both
echo $a->$foo;
echo $a->foo;
Follow the manual about variable variables

Well, in order to fully understand the somewhat odd-looking $object->$foo, you should understand two things about PHP:
Variable names
Most of the time variables in PHP are quite straight-forward. They begin with a $ sign, have one [a-zA-Z_] character, and then any amount of [a-z-A-Z0-9_] characters. Examples include:
$var = 'Abcdef';
$_GET = [];
$a1 = 123;
// And so on...
Now, PHP variables can actually be named pretty much anything, as long as the name is, or can be cast to, a scalar type. The way you name a variable with anything is to use curly braces ({}), like this:
${null} = 'It works'; echo ${null};
${false} = 'It works'; echo ${false};
${'!'} = 'It works'; echo ${'!'};
// Slightly weirder...
${(int)trim(' 5 ')} = 'It works'; echo ${5};
${implode(['a','b','c'])} = 'It works'; echo $abc;
Important: Just because you can do this does not mean you should, however. It is mostly just an oddity of PHP that you can do this.
Variable variables
A somewhat convoluted explanation: A variable variable is a variable that is accessed using a variable name.
A much easier way to understand variable variables is to use what we just learning about variable names in PHP. Take this example:
${"abc"} = 'Abc...';
echo $abc;
We create a variable using the string, "abc", which can also be accessed using $abc.
Now, there is no reason (or rule) that says it has to be a string.... it can also be a variable:
$abc = 'Abc...';
$varName = 'abc';
echo ${$varName}; // echo $abc
That is basically a variable variable. "Real" variable variables just do not use the curly braces:
$abc = 'Abc...';
$varName = 'abc';
echo $$varName; // echo $abc
As for the question
In the question the $object->$foo thing is basically just an "object variable variable", if you like
$object = new stdClass;
$object->abc = 'The alphabet!';
$foo = 'abc';
echo $object->$foo;
echo $object->{$foo}; // The same
echo $object->{'abc'}; // The same
Object variable variables can be somewhat useful, but they are rarely necessary. Using an associative array is usually a better choice.

Related

Add two $row together in one php echo

I'm not even sure if what I am trying to do is possible, I have a simple php echo line as below..
<?php echo $T1R[0]['Site']; ?>
This works well but I want to make the "1" in the $T1R to be fluid, is it possible to do something like ..
<?php echo $T + '$row_ColNumC['ColNaumNo']' + R[0]['Site']; ?>
Where the 1 is replaced with the content of ColNaumNo i.e. the returned result might be..
<?php echo $T32R[0]['Site']; ?>
It is possible in PHP. The concept is called "variable variables".
The idea is simple: you generate the variable name you want to use and store it in another variable:
$name = 'T'.$row_ColNumC['ColNaumNo'].'R';
Pay attention to the string concatenation operator. PHP uses a dot (.) for this, not the plus sign (+).
If the value of $row_ColNumc['ColNaumNo'] is 32 then the value stored in variable $name is 'T32R';
You can then prepend the variable $name with an extra $ to use it as the name of another variable (indirection). The code echo($$name); prints the content of variable $T32R (if any).
If the variable $T32R stores an array then the syntax $$name[0] is ambiguous and the parser needs a hint to interpret it. It is well explained in the documentation page (of the variable variables):
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.
You can do like this
$T1R[0]['Site'] = "test";
$c = 1;
$a = "T".$c."R";
$b = $$a;
echo "<pre>";
print_r($b[0]['Site']);
Or more simpler like this
$T1R[0]['Site'] = "test";
$c = 1;
$a = "T".$c."R";
echo "<pre>";
print_r(${$a}[0]['Site']);

PHP help - only need a simple explanation

Alright, I'm trying to understand how this PHP code works.
<?php
$test = "success";
$primary = "test";
$id = ${$primary};
echo $id;
?>
I know the output is "success" but I don't understand how it works.
What i understand so far:
test variable has the string "success",
primary variable has the string "test",
'id' variable has the string of the first variable in the list (the test variable),
print the string in the 'id' variable.
I'm confused because i don't know what the primary variable is doing in the braces within the id variable.
A simple explanation would be appreciated.
This is a concept called variable variables.
It means that at runtime, if multiple variable indicators $ are present, PHP will attempt to associate them in a cascading manner.
For example, take the following:
$a = "b";
$b = "c";
$c = "d";
echo $$$a;
PHP will systematically go through the echo statement to determine what the actual value is, as such:
$$$a is equivalent to $$("b") (because $a is "b")
...which is equivalent to $("c") (because $b is "c")
...which is finally equivalent to "d"
In your example, you're given a variable assignment to something that, in essence, is like ${$a}. In PHP, braces are used to isolate variables within strings, but can be used on their own to denote a variable explicitly, so ${$a} is exactly equivalent to $$a in this case.
$id = ${$primary};
try to parse from right to left $primary = 'test'
so ${$primary} is now $test
so equation becomes $id = $test;
$id = $test = success
Know more about variables variables on the link provided by other users
This is a variable variable.
$test = "success";
$primary = "test";
//${$primary} means $test here, because value of $primary is "test".
//It is equal to $$primary
$id = ${$primary};
echo $id; //Prints "success"
http://php.net/manual/en/language.variables.variable.php

Using array value with index as Variable Variable

The title may be a little confusing. This is my problem:
I know you can hold a variable name in another variable and then read the content of the first variable. This is what I mean:
$variable = "hello"
$variableholder = 'variable'
echo $$variableholder;
That would print: "hello". Now, I've got a problem with this:
$somearray = array("name"=>"hello");
$variableholder = "somearray['name']"; //or $variableholder = 'somearray[\'name\']';
echo $$variableholder;
That gives me a PHP error (it says $somearray['name'] is an undefined variable). Can you tell me if this is possible and I'm doing something wrong; or this if this is plain impossible, can you give me another solution to do something similar?
Thanks in advance.
For the moment, I could only think of something like this:
<?php
// literal are simple
$literal = "Hello";
$vv = "literal";
echo $$vv . "\n";
// prints "Hello"
// for containers it's not so simple anymore
$container = array("Hello" => "World");
$vv = "container";
$reniatnoc = $$vv;
echo $reniatnoc["Hello"] . "\n";
// prints "World"
?>
The problem here is that (quoting from php: access array value on the fly):
the Grammar of the PHP language only allows subscript notation on the end of variable expressions and not expressions in general, which is how it works in most other languages.
Would PHP allow the subscript notation anywhere, one could write this more dense as
echo $$vv["Hello"]
Side note: I guess using variable variables isn't that sane to use in production.
How about this? (NOTE: variable variables are as bad as goto)
$variablename = 'array';
$key = 'index';
echo $$variablename[$key];

Making a variable out of another variables' value in php (php basics)

I need to make a dynamic variable based on a loop, what i am looking for is a variable something like
$var = "foo";
$$var = "bar";
echo $foo; // bar
but for me it should be more like a fixed parameter attached to the dynamic part like
$var='123';
$'current_'.$$var=some value; // not correct syntax
echo $current_123 should give 'some value';
Use curly braces:
$${'current_' . $var} = $some_value;

PHP Syntax ${"{$type}_method"}

I've been reading an PHP5 book, and the author commonly used this syntax
${"{$something}_somethingelse"};
I have no idea what that means. Does it dynamically generate a variable name?
Someone help me out?
It is a language feature called Variable variables.
Consider the following piece of code:
$a = 'hello';
This is pretty straight forward. It creates the variable $a and sets its value to 'hello'.
Let's move on with:
$$a = 'world';
${$a} = 'world';
Basically, since $a = 'hello', those two statement are the equivalent of doing:
$hello = 'world';
So the following:
echo "$a ${$a}";
Is the equivalent of doing:
echo "$a $hello";
Braces { }
The braces are used to prevent ambiguity problems from occurring. Consider the following:
$$a[1] = 'hello world';
Do you want to assign a variable named after the value of $a[1] or do you want to assign the index 1 of the variable named after $a?
For the first choice, you would write it as such:
${$a[1]} = 'hello world';
For the second choice:
${$a}[1] = 'hello world';
Your example
Now, for your example.
Let's consider that:
$something = 'hello';
Using your example as such:
${"{$something}_somethingelse"} = 'php rocks';
Would essentially be equivalent of doing:
$hello_somethingelse = 'php rocks';
They are 'variable variables'. See this.
Brackets allow you to make more advanced variable names. It your Case if $something was equal to test it would be:
${"test_somethingelse"};
Which is just an advanced variable name.
Here is an example.
$test = "test";
${"test_test"} = "test2";
echo $test; // prints test
echo ${"test_test"}; // prints test2
Using Variable Varaibles, as everyone else mentioned, you can create variables based on other variables. So in your case, he was making a variable based on $something's value
$something = "test";
${"{$something}_somethingelse"};
turns into
${"test_somethingelse"};
That will replace the {$something} with the value of $something.
I think the inner curly braces are just for readability and to help when doing $object->property etc.
Because it seems to be also in a variable, that is called a variable variable.
For example,
$foo = 'bar';
$$foo = 7;
echo $bar;
// produces 7;

Categories