php function declaration in afterSave(&$record) problem
Archived from the Xataface Users forum.
fabien_ecl — Tue Nov 23, 2010 11:55 pm
I create a function to generate automated result in a column of a table.
In fact I have the following table : id;task;duration;cost
The last column (cost) is generated automatically from duration and a number that is determined by task value. For doing that i use a php function of time conversion.
I use function afterSave(&$record) to do that and it works when I create an item or modify one item. But when I’m doing multiple update (several items update at once) I have the following error :Fatal error: Cannot redeclare time_to_sec() (previously declared in……). I implement this time_to_sec function directly in the code (ie I do not use function but use implements it contents directly in the code where I need it…) and it works but it seems that php function declaration doesn’t work in function afterSave(&$record) with multiple update.
The code :
- Code: Select all
function afterSave(&$record){ //PHP conversion of SQL time format to seconds function time_to_sec($time) { $hours = substr($time, 0, -6); $minutes = substr($time, -5, 2); $seconds = substr($time, -2); return $hours * 3600 + $minutes * 60 + $seconds; } Here 40 lines of code with one using time_to_sec function
Any idea of a way to use php function without implementing it directly in the code.
shannah — Wed Nov 24, 2010 11:52 am
PHP isn’t a dynamic language like some others (like javascript) so you can only declare a function once - and all functions are placed in the global scope.
In this case since your timetosec function is placed inside the afterSave() method, it is re-declared every time the afterSave() method is run… so after the first time PHP will complain that you’re declaring a function that already exists.
Solution: Declare your timetosec function somewhere in the global scope where it will only be run once. (e.g. at the beginning of your index.php file, or place it in another file that you include in your index.php file.
-Steve
fabien_ecl — Wed Nov 24, 2010 2:01 pm
Sure,
i’m going back to my php basics…
Thanx for answering such a newbie question.