Click to See Complete Forum and Search --> : [RESOLVED] Storing functions in a variable


CWCJimmy
08-03-2006, 03:24 PM
Is it possible to store a function itself NOT the value that it returns in a variable?

I'm trying to create an array I can use to formulate insert statements, but I need to calculate the data for the insert statements. I don't want to have to edit 3 places when I want to add a field or change a calculation.

Something like this:


$columns = array
(
[FIELD1] => CALCULATION / FUNCTION,
[FIELD2] => CALCULATION / FUNCTION
);



Any ideas?

NogDog
08-03-2006, 05:34 PM
It's not clear to me why you would need to do this, but assuming I'm just not grasping your intention, perhaps you could store the function names in the array:

$functions = array (
['f1'] => 'function_one',
['f2'] => 'function_two',
['f3'] => 'function_three'
);

Then anywhere you need to use function_two(), for example:

call_user_func($functions['f2'], $param1, $param2);

But as I said, it's not really clear to me what you want, so I may be totally off-base here.

CWCJimmy
08-04-2006, 09:56 AM
Thanks for the response.

I apologize that wasn't a very clear post. Let me try to re-explain what I'm trying to do. I'm dumping data from an source via ODBC to a MySQL database. I had an array that contained the Fieldname it's datatype and an SQL statement to get it's value. Like so:

$mysql_table= array (
"TableName" => array (
"SKU" => array (
"Datatype" => "VARCHAR(20)",
"SQL" => "TRIM(ItemNumber)"),
"DESCP_1" => array (
"Datatype" => "VARCHAR(255)",
"SQL" => "TRIM(ItemDescription)"),
"IMG_EXIST" => array (
"Datatype" => "INT(15)",
"SQL" => "IF(ImageFile = '', 'N', 'Y')")
)
);


This was used to create the table and insert statements for MySQL. This, however, will no longer work becuase the ODBC driver does not support all of the functions I need. So I was hoping to replace the SQL functions with functions in PHP so I could achieve the same result. Like so:


$mysql_table= array (
"TableName" => array (
"SKU" => array (
"Datatype" => "VARCHAR(20)",
"SQL" => trim($value)),
"DESCP_1" => array (
"Datatype" => "VARCHAR(255)",
"SQL" => trim($value)),
"IMG_EXIST" => array (
"Datatype" => "INT(15)",
"SQL" => empty($value) ? 'N' : 'Y'))
)
);


But to do that I would need to store the function/calculation itself, and not just the result that the it returned becuase this array would be declared outside the function it is to be used in.

The whole reason I want to do it this way is because this way I can easily add/remove/edit fields by editing one place.

Hope that makes a bit more sense

CWCJimmy
08-09-2006, 04:43 PM
Not to bring a dead topic back but I found what I was looking for and I figured it may help someone.

I stumbled across this create_function (http://us3.php.net/manual/en/function.create-function.php) function on the PHP website. You can literally write the syntax for the functions and have the syntax stored in a variable.

Pretty slick.