Reputation: 5126
I'm writing a PHP script that accesses two different data objects - one is backed by a DB, the other contains session data. They both contain the same fields - i.e. the data that is in the session object will make its way into the DB once it is validated.
I'm trying to write a function that will first check the db-backed object for a value, then check the session-data-backed object for a value. It's not working like I quite expect, however. Here is what I have.
<?php
function check_cache($field){
// $App is the DB backed object, $data is the session object
return $app->$field ? $app->$field : $data->$field ? $data->$field : '';
}
?>
I'd like to be able to call the function like this:
<input type="text" value="<?php echo check_cache('address'); ?>" />
...but the function always returns nothing. When I replace the function call with the actual inline code, substituting $field
with the field name I want, it works. What am I missing?
Upvotes: 1
Views: 537
Reputation: 2894
You should ensure that $app and $data exist within the scope of the function (potential by passing them as parameters, I'll leave that to you). Try this:
<?php
function check_cache($field){
// $App is the DB backed object, $data is the session object
return $app->${$field} ? $app->${$field} : $data->${$field} ? $data->${$field} : '';
}
?>
You should probably extend this though to ensure that $app->$$field exists, etc.
Edit:
This is pretty wrong, as pointed out by bob-the-destroyer in the comments. $app->$field
is all you need. Just make sure the scope is right, and the members you want aren't private. Apologies.
Upvotes: 1
Reputation: 6113
I'd be tempted to say it's a scope issue, $app + $data don't exist inside the function, only outside. Extend the function to take two extra params, and pass in the $app + $data objects that way.
Addendum
This won't entirely fix the problem, you'll still need to access the fields of the object, depending on your class structure, if it's properties are private, will make some of the alternate answers not work, as the field won't be accessible via the obj->field syntax.
Upvotes: 0
Reputation: 57316
You can try something like this:
<?php
function check_cache($field){
global $app, $data;
// $App is the DB backed object, $data is the session object
$av = eval("\$app->".$field);
$dv = eval("\$data->".$field);
return $av ? $av : $dv ? $dv : '';
}
?>
Upvotes: 0