Access object attribute with variable? - php

Not sure if the title is exactly what i want to do. Below is my working code.
mysql_select_db($_POST[database]);
$table_list = mysql_query('SHOW TABLES');
$tables_in_db = "Tables_in_" . $_POST[database];
while ($row = mysql_fetch_object($table_list)) {
echo "<tr>
<td class='pageBody'>" . $row->$tables_in_db . "</td>
</tr>";
}
Is it possible to remove line 4 and access the object attribute with $row->Tables_in_{$_POST[database]} in some manner? I've tried a couple different ways including various placing of quotes and curly braces, i had to resort to assigning the whole attribute to the variable $tables_in_db and then use that variable to access the attribute.

You have the right idea, just not the proper syntax. Variable properties can either take the form of a single variable ($a->$b) or some other expression that returns a string containing the name of the property ($a->{'b'}).
$row->{'Tables_in_' . $_POST['database']}
Aside: using one of the other mysql_fetch_* functions, knowing the column name would become irrelevant. For example, mysql_fetch_array() or mysql_fetch_row() and accessing the $row[0] item.

Related

Variable Variables with array element values syntax

I want to create a session variable but the session variable name I want to be dynamic. So what I need is the proper syntax for a variable name that is a $_SESSION variable.
I have tried the code below which creates a variable variable name and stored a value to it and it works just fine.
$xvalue = $_SESSION['delivery_id'];
$delivery_string = 'this_delivery_id_' . $xvalue ;
$$delivery_string = $_SESSION['delivery_id'];
echo "Variable name: " . $delivery_string . "<br/>";
echo "Session Variable Value: " . $this_delivery_id_29 . "<br/>";
The above code echos 29 for line 5; the desired result.
So working upon what worked with a variable variable I then just tried to make the variable name a $_SESSION variable name instead.
$value = $_SESSION['delivery_id'];
$xsession = "$_SESSION[\"" . $value . "\"]"; // this gives compilation error so dead stop. I also tried without the escapes and also a dead stop. I also tried escaping the [ and ] and got rid of the compilation error so the code runs but it does not give the desired result.
$$xsession = $_SESSION['delivery_id'];
echo "Variable name: " . $xsession . "<br/>";
echo "Session Variable Value: " . $_SESSION["delivery_id_29"] . "<br/>";
So line 2 of the code is where the problem is.
The issue comes from trying to interpolate the variable a little "too hard," if you escape $_SESSION[$value] you'll be left with the string "$_SESSION[$value]", which is not a valid name for a variable - you're attempting to access the variable as if it were defined like so: $$_SESSION[$value] = 'foo';. What you want to be doing is taking the value of that array element and using that in the variable variable, which needs to be done by referencing it.
Either of the following seem to give the result you are going for; a straight variable variable:
$value = 'foo';
$_SESSION['foo'] = 'bar';
$bar = 'baz';
echo ${$_SESSION[$value]}; //prints baz
One with another step, aiding in making it more clear:
$identifier = $_SESSION[$value];
echo $$identifier //prints baz
I don't understand what you would be storing in this manner, but you may also investigate alternatives to achieve a cleaner, more straight-forward approach. If you clarify your use behind this, maybe someone will be able to suggest an alternative methodology.

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 numeric Variable Name

I want to append some $variables automaticly and set their names numeric
I have a script look like this:
<?php
$i=0;
while($i<=100){
$variable_[$i]=$i;
$i++;
#with "[$i]" I mean their name will be $variable_1 , $variable_2, $variable_3 ...
#they will be automatic increased variables non manual!
}
?>
This is called variable variables.
You can set a variable variable by defining its name inside a variable, such as:
$name = 'variable_' . $i;
and then assign a value to it by doing:
$$name = $i;
Note that variable variables can easily be misused. Make sure you completely understand the repercussions of this feature on your code and the risk of having bugs, and ensure this is the only solution you have, i.e. you can't use an array ($variables[$i] = $i;) instead.
Its better to use Array with key=> value pair. You can build this array dynamically and then loop through it by using foreach.

Purpose of complex (curly) syntax outside a string representation

I understand the usage of complex (curly) syntax within a string, but I don't understand it's purpose outside of a string.
I just found this code in CakePHP that I cannot understand:
// $class is a string containg a class name
${$class} =& new $class($settings);
If somebody could help me understand why is used here, and what is the difference between this and:
$class =& new $class($settings);
Thank you.
Easiest way to understand this is by example:
class FooBar { }
// This is an ordinary string.
$nameOfClass = "FooBar";
// Make a variable called (in this case) "FooBar", which is the
// value of the variable $nameOfClass.
${$nameOfClass} = new $nameOfClass();
if(isset($FooBar))
echo "A variable called FooBar exists and its class name is " . get_class($FooBar);
else
echo "No variable called FooBar exists.";
Using ${$something} or $$something. is referred to in PHP as a "variable variable".
So in this case, a new variable called $FooBar is created and the variable $nameOfClass is still just a string.
An example where the usage of the complex (curly) syntax outside of a string would be necessary is when forming a variable name out of an expression, consisting of more than just one variable. Consider the following code:
$first_name="John";
$last_name="Doe";
$array=['first','last'];
foreach ($array as $element) {
echo ${$element.'_name'}.' ';
}
In the code above the echo statement will output the value of the variable $first_name during the first loop, and the value of the variable $last_name during the second loop. If you were to remove the curly brackets the echo statement would try to output the value of the variable $first during the first loop and the value of the variable $last during the second loop. But since these variables were not defined the code would return an error.
The first example creates a dynamically named variable (name is the value of the class variable), the other overwrites the value of the class variable.

variable value is two strings

Somehow a variable that SHOULD contain only one string (not an array or anything) contain an url, managed to contain two different values;
string(8) "value 1 " string(7) "value 2"
i cannot use this variable because echoing it or using it in another function would print
value 1 value2
which is not what i need, i need only value 1 and i cannot use $var[0]
Two things; how can i do something similar (one variable two strings), and how can i manipulate it.
EDIT : here is the code
public function get_first_image($post) {
$image_id=get_post_thumbnail_id($post->id);
$image_url = wp_get_attachment_image_src($image_id,’large’);
$image_url=$image_url[0];
var_dump($image_url);
return $image_url;
}
the var_dump() results are as mentioned above
Best Regards
Don't reuse $image_url as a variable, this is most likely causing your problem.
You should rename one of your variables:
public function get_first_image($post) {
$image_id = get_post_thumbnail_id($post->id);
$image_array = wp_get_attachment_image_src($image_id,’large’);
$image_url = $image_array[0];
var_dump($image_url);
return $image_url;
}
You question doesn't give a great amount of detail. If you need access to part of a string you can use the explode() function. So if the string contained no spaces between the separate values, you could use $newstring = explode(" ",$oldstring); echo $newstring[0]; This would then give you access to the first part of the string.
I'd recommend you look up string concatenation.
If you can give us further details, we may be able to assist you further.

Categories