Dynamic Naming of PHP Objects - php

How do i dynamically assign a name to a php object?
for example how would i assign a object to a var that is the id of the db row that i am using to create objects.
for example
$<idnum>= new object();
where idnum is the id from my database.

You can use the a double dollar sign to create a variable with the name of the value of another one for example:
$idnum = "myVar";
$$idnum = new object(); // This is equivalent to $myVar = new object();
But make sure if you really need to do that, your code can get really messy if you don't have enough care or you abuse of using this "feature"...
I think you can better use arrays or hash tables rather than polluting the global namespace with dynamically created variables.

this little snippet works for me
$num=500;
${"id$num"} = 1234;
echo $id500;
basically just use the curly brackets to surround your variable name and prepend a $;

You can do something like this:
${"test123"} = "hello";
echo $test123; //will echo "hello"
$foo = "mystring";
${$foo} = "a value";
echo $mystring; //will echo "a value";

http://us2.php.net/language.variables.variable

Related

Get a variable name from database

I'm a little confused - how do I get a variable name stored to a database?!
Record in the database is a string: "$test"
The variable $user is set before the records a fetched from database. So I want to "convert" this string to a real variable to get the value of it.
The following didn't work:
// $test is set to 'bla'
$test = 'bla';
// $var is the value from the database
$var = '$test';
// print $test
echo ${$var};
I know that it would work if I remove the '$' from the database record
$var = 'test';
echo $$var;
But how to handle this without?
String replace in better option, if you don't want to replace $ you can use eval function:
$test = 'bla';
$var = '$test';
eval("\$var = \"$var\";");
echo $var; //output: bla
I was facing a similar problem just now.
Here is what I did:
$res[0] is obtained from mysql_fetch_array() and it contains another query which has $variable embedded.
$qry="select query from sql_list where id=".$sql_id;
$result=mysql_query($qry);
$res=mysql_fetch_array($result);
eval("\$qry_2 = \"$res[0]\";");
mysql_query($qry_2)
It works! Maybe someone can suggest a better way.
This is 3 years later but since no one give you your answer, maybe this will help you or the next person searching for this.
From what I understand, you already declared a variable and stored the name of that var in the db.
$var = '$test'; // from db
$var[0] = ''; // remove first letter, simple & much faster than ( trim or substr )
//content of var
$var_content = ${$var};

Create a property of object with the value of variable [duplicate]

How do i dynamically assign a name to a php object?
for example how would i assign a object to a var that is the id of the db row that i am using to create objects.
for example
$<idnum>= new object();
where idnum is the id from my database.
You can use the a double dollar sign to create a variable with the name of the value of another one for example:
$idnum = "myVar";
$$idnum = new object(); // This is equivalent to $myVar = new object();
But make sure if you really need to do that, your code can get really messy if you don't have enough care or you abuse of using this "feature"...
I think you can better use arrays or hash tables rather than polluting the global namespace with dynamically created variables.
this little snippet works for me
$num=500;
${"id$num"} = 1234;
echo $id500;
basically just use the curly brackets to surround your variable name and prepend a $;
You can do something like this:
${"test123"} = "hello";
echo $test123; //will echo "hello"
$foo = "mystring";
${$foo} = "a value";
echo $mystring; //will echo "a value";
http://us2.php.net/language.variables.variable

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 object properties

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.

PHP Variable Variables

How does php handle something like this...
$blah = "Testing a variable";
$$blah = "test";
What would my new variable name be?
Everything you need to know about variable variables at http://www.php.net/manual/en/language.variables.variable.php, except for one thing: don't use them.
echo ${'Testing a variable'};
However, you don't want to do this in practice. It makes for unmaintainable, bug-prone code.
The variable $blah must contain a valid variable name.
This will tell you about variables: http://www.php.net/manual/en/language.variables.basics.php
Not really an answer, but...
<?php
function I_love_you()
{
return "haha";
}
$haha = "HoHoHo";
$tom = "I_love_you";
$blah = "tom";
echo ${$$blah()};
?>

Categories