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?
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:
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->$fieldis all you need. Just make sure the scope is right, and the members you want aren’t private. Apologies.