473,769 Members | 4,909 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Program flow question

A scripting newbie question... I'm trying to understand some code I found.
This script conducts a poll and writes the results to a text file. The
following statement is part of the source file. The exact code is not important
to my question so don't wrack your brain on this.

if (isset($votings tep)) {
function ShowTheStuff($i tem, $itemvoted, $graph_width, $graph_height) {
$hector=count($ itemvoted);$tot alvotes=0;$in=0 ;$stepstr='';
$totalvotes=Sum Array($itemvote d);
$in=0;
if ($totalvotes==0 ) { $totalvotes=0.0 001; }
while ($in<$hector) {
$stepstr=$steps tr.stripslashes ($item[$in]).':
'.(int)(($itemv oted[$in]/$totalvotes)*10 0).'%<br>';
$timesred=(int) ((($itemvoted[$in]/$totalvotes))*$ graph_width);
$stepstr=$steps tr.'<img height='.$graph _height.'
width='.$timesr ed.' src="lp_1.gif"> <img
height='.$graph _height.' width='.($graph _width-$timesred).'
src="lp_0.gif"> <br><br>';
$in++;
}
return $stepstr;
}
}

My question is this. A function is contained with an 'if' statement. How does
this work? I've never seen this before in any non-scripting language. This
function 'ShowTheStuff' is called further down in the file.

In the flow of the program as it falls thru line by line, if it meets the 'if'
condition then it hits the function, which it can't call because it doesn't have
the parameters. What's the point?

Further along in the program when the 'ShowTheStuff' function gets called, how
is it able to call it when it's another block of code (the 'if' block)? Or is
it able to call it but it must meet the 'if' condition?

This makes no sense to me. What is the flow of execution here?

Thanks for your help.
Jul 17 '05 #1
4 2314
Bruce W...1 wrote:
A scripting newbie question... I'm trying to understand some code I found.
This script conducts a poll and writes the results to a text file. The
following statement is part of the source file. The exact code is not important
to my question so don't wrack your brain on this.

if (isset($votings tep)) {
function ShowTheStuff($i tem, $itemvoted, $graph_width, $graph_height) {
$hector=count($ itemvoted);$tot alvotes=0;$in=0 ;$stepstr='';
$totalvotes=Sum Array($itemvote d);
$in=0;
if ($totalvotes==0 ) { $totalvotes=0.0 001; }
while ($in<$hector) {
$stepstr=$steps tr.stripslashes ($item[$in]).':
'.(int)(($itemv oted[$in]/$totalvotes)*10 0).'%<br>';
$timesred=(int) ((($itemvoted[$in]/$totalvotes))*$ graph_width);
$stepstr=$steps tr.'<img height='.$graph _height.'
width='.$timesr ed.' src="lp_1.gif"> <img
height='.$graph _height.' width='.($graph _width-$timesred).'
src="lp_0.gif"> <br><br>';
$in++;
}
return $stepstr;
}
}

My question is this. A function is contained with an 'if' statement. How does
this work? I've never seen this before in any non-scripting language. This
function 'ShowTheStuff' is called further down in the file.


Aaargghh! I'm sure that's a 'really bad idea(tm)'. I'm not sure what
they were thinking of to allow that sort of thing. It would certainly
not be possible in a compiled language.

It appears that you can conditionally define functions (and classes) at
execution time allowing, for example:

$adding = $_REQUEST['adding'];

if ($adding) {
function calc($a,$b) {
return $a+$b;
}
} else {
function calc($a,$b) {
return $a-$b;
}
}

echo calc(1,4);

I really don't recommend doing it though. A function should really have
one and only one definition. It's too confusing otherwise.

Jul 17 '05 #2
Bruce W...1 wrote...
A scripting newbie question... I'm trying to understand some code I found. [...] if (isset($votings tep)) {
function ShowTheStuff($i tem, $itemvoted, $graph_width, $graph_height) { [...] return $stepstr;
}
}

My question is this. A function is contained with an 'if' statement.
How does this work?
Eh! this is fun :-)

The function declared within the if only gets defined after execution
goes through the if block.

In the flow of the program as it falls thru line by line, if it meets
the 'if' condition then it hits the function, which it can't call
because it doesn't have the parameters. What's the point?
The function does not get called when it is defined.
Before the execution gets there, there is no function named "ShowTheStu ff";
after the if gets executed that function is defined.

Further along in the program when the 'ShowTheStuff' function gets
called, how is it able to call it when it's another block of code
(the 'if' block)?
Once the function gets defined, it can be called from anywhere.
The problem is if the function didn't get defined because the
if condition failed: in that case you'll get a "undefined function"
error.
Or is it able to call it but it must meet the 'if' condition?
The function must be defined before it gets called.

This makes no sense to me. What is the flow of execution here?


Must be a code obfuscation technique :-)
I think the way php works is this:
1. read all the script defining all "properly" declared functions
2. execute instructions from the top
3. if another function is found define it and continue

On step 3 one bad thing may happen:
+ the function may have been defined previously, which
will trigger an error
I made this smallish script to find out how functions
inside code blocks work:

<?php
$funs = get_defined_fun ctions();
echo '<pre>1st pass $funs[\'user\'] '; print_r($funs['user']); echo '</pre>';

define('DEBUGGI NG', 'browser');

function normalway($p) {
function internal1() {} // empty function
switch (DEBUGGING) {
case 'browser':
echo $p, ' in normalway()<br />'; break;
case 'logfile':
error_log("$p in normalway()\n", 3, '/var/log/debug.log'); break;
default:
// do nothing :-)
}
}

$funs = get_defined_fun ctions();
echo '<pre>2nd pass $funs[\'user\'] '; print_r($funs['user']); echo '</pre>';

// unusual way :-)
switch (DEBUGGING) {
case 'browser':
function unusualway($p) {
function internal2() {} // empty function
echo $p, ' in unusualway()<br />';
}
break;
case 'logfile':
function unusualway($p) {
function internal3() {} // empty function
error_log("$p in unusualway()\n" , 3, '/var/log/debug.log');
}
break;
default:
function unusualway($p) {
function internal4() {} // empty function
// do nothing :-)
}
}

$funs = get_defined_fun ctions();
echo '<pre>3rd pass $funs[\'user\'] '; print_r($funs['user']); echo '</pre>';

if (!isset($UNVAR) ) {
normalway('UNVA R is unset'); // also defines internal1()
unusualway('UNV AR is unset'); // also defines internalN()
}

$funs = get_defined_fun ctions();
echo '<pre>4th pass $funs[\'user\'] '; print_r($funs['user']); echo '</pre>';

function lastfunction() {} // another empty function
?>
Jul 17 '05 #3
hexkid wrote:

Bruce W...1 wrote...
A scripting newbie question... I'm trying to understand some code I found.

[...]
if (isset($votings tep)) {
function ShowTheStuff($i tem, $itemvoted, $graph_width, $graph_height) {

[...]
return $stepstr;
}
}

My question is this. A function is contained with an 'if' statement.
How does this work?


Eh! this is fun :-)

The function declared within the if only gets defined after execution
goes through the if block.
In the flow of the program as it falls thru line by line, if it meets
the 'if' condition then it hits the function, which it can't call
because it doesn't have the parameters. What's the point?


The function does not get called when it is defined.
Before the execution gets there, there is no function named "ShowTheStu ff";
after the if gets executed that function is defined.
Further along in the program when the 'ShowTheStuff' function gets
called, how is it able to call it when it's another block of code
(the 'if' block)?


Once the function gets defined, it can be called from anywhere.
The problem is if the function didn't get defined because the
if condition failed: in that case you'll get a "undefined function"
error.
Or is it able to call it but it must meet the 'if' condition?


The function must be defined before it gets called.
This makes no sense to me. What is the flow of execution here?


Must be a code obfuscation technique :-)
I think the way php works is this:
1. read all the script defining all "properly" declared functions
2. execute instructions from the top
3. if another function is found define it and continue

On step 3 one bad thing may happen:
+ the function may have been defined previously, which
will trigger an error

I made this smallish script to find out how functions
inside code blocks work:

<?php
$funs = get_defined_fun ctions();
echo '<pre>1st pass $funs[\'user\'] '; print_r($funs['user']); echo '</pre>';

define('DEBUGGI NG', 'browser');

function normalway($p) {
function internal1() {} // empty function
switch (DEBUGGING) {
case 'browser':
echo $p, ' in normalway()<br />'; break;
case 'logfile':
error_log("$p in normalway()\n", 3, '/var/log/debug.log'); break;
default:
// do nothing :-)
}
}

$funs = get_defined_fun ctions();
echo '<pre>2nd pass $funs[\'user\'] '; print_r($funs['user']); echo '</pre>';

// unusual way :-)
switch (DEBUGGING) {
case 'browser':
function unusualway($p) {
function internal2() {} // empty function
echo $p, ' in unusualway()<br />';
}
break;
case 'logfile':
function unusualway($p) {
function internal3() {} // empty function
error_log("$p in unusualway()\n" , 3, '/var/log/debug.log');
}
break;
default:
function unusualway($p) {
function internal4() {} // empty function
// do nothing :-)
}
}

$funs = get_defined_fun ctions();
echo '<pre>3rd pass $funs[\'user\'] '; print_r($funs['user']); echo '</pre>';

if (!isset($UNVAR) ) {
normalway('UNVA R is unset'); // also defines internal1()
unusualway('UNV AR is unset'); // also defines internalN()
}

$funs = get_defined_fun ctions();
echo '<pre>4th pass $funs[\'user\'] '; print_r($funs['user']); echo '</pre>';

function lastfunction() {} // another empty function
?>

=============== =============== =============== ==============

You may have hit the nail on the head, i.e. not defining a function unless it is
going to be used. I'll need to study the code further to see if this is the
case.

If this is the case then would any increased speed be realized? Is this a
worthwhile practice?

Thanks.
Jul 17 '05 #4
Bruce W...1 wrote:
You may have hit the nail on the head, i.e. not defining a function unless it is
going to be used. I'll need to study the code further to see if this is the
case.

If this is the case then would any increased speed be realized? Is this a
worthwhile practice?


hmmm ... I don't think so.
However, I do think that in

<?php
define('DEBUGGI NG', 'browser');

switch (DEBUGGING) {
case 'browser':
function debug_1($x) {
echo 'DEBUG: x = [', $x, ']');
} break;
case 'log':
funtion debug_1($x) {
error_log('DEBU G: ' . $x, 3, '/var/log/debug.log');
} break;
case 'mail':
funtion debug_1($x) {
mail('admin', 'debug', 'x = ' . $x);
} break;
}

function debug_2($x) {
switch (DEBUGGING) {
case 'browser':
echo 'DEBUG: x = [', $x, ']'); break;
case 'log':
error_log('DEBU G: ' . $x, 3, '/var/log/debug.log'); break;
case 'mail':
mail('admin', 'debug', 'x = ' . $x); break;
}
}
?>

debug_1() will be faster than debug_2(), even accounting for the
processing PHP must do to define it and especially if you call
debug_1() a lot.
--
I have a spam filter working.
To mail me include "urkxvq" (with or without the quotes)
in the subject line, or your mail will be ruthlessly discarded.
Jul 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
4649
by: Albert Ahtenberg | last post by:
Hello, I had some bad experience with code organization and script functionality in writing my php based applications. And as the applications get bigger in scale it gets even worse. Therefore, I am trying to build a general schema for data flow in a php/mysql application. What I has in mind is to design a three major units. To handle the input, processing and data access. Plus another unit to generate the output.
11
7241
by: Robert Bowen | last post by:
Hello all. I have been given mock-ups (in static HTML) of some pages for a site I am working on. The client would like these pages to look exactly as they do now. The problem is that the content is dynamic, it comes from a database. My question -- with CSS (because with HTML tables I don't think it's possible) how can I make my text "flow" in two columns? eg. If there are 100 lines of content, I would like 50 to be in the 1st column, and...
54
4116
by: bnp | last post by:
Hi, I took a test on C. there was an objective question for program output type. following is the program: main() { char ch; int i =2;
34
2450
by: kevin.watters | last post by:
Hi all, I have a need for a short program: Given a drive letter, it would recursively search through all directories, "generating" each filename that it encounters (need to pass each filename to a function). Can't help but think this "utility" already exists but f**ked if I can find it.
1
2012
by: Brett | last post by:
I'd like to have all of my documentation in one place. I use the following for documenting code: - attributes for certain types of documentation - use of the C# generated inline XML documentation - simple comments I also use Visual Paradigm for UML (class relationships), which integrates with VS.NET. I need something for general documentation of program flow. Any suggestions on what to use for this?
8
3122
by: lovecreatesbea... | last post by:
K&R 2, sec 2.4 says: If the variable in question is not automatic, the initialization is done once only, conceptually before the program starts executing, ... . "Non-automatic variables are initialized before the program starts executing." -- What does this mean? What is the name of the stage in which the mentioned initialization is performed? Compile-time or run-time? In the following snippet, variables b and c are defined at line 7...
18
2178
by: Andrew Gentile | last post by:
Hello, I would like to find a way of using scanf() and the Enter key to have user-controlled program flow. Currently, I have a couple of lines in my program which serves as a pause in the program. printf("\n\tTo continue, press any key followed by Enter: "); scanf("%i",&temp); This works as a program pause, but it requires that the user enter a
6
2440
by: Crooter | last post by:
Hello colleagues, Could anybody tell me if there are existing open-source solutions to extract the program tree using a program source code? I'm aware that GCC has program flow information and tree respectively for optimization, but I'm looking for something less complicated. An ideal case would be a small program based on a parser with YACC compatible grammar which extracts the program flow tree. Best regards,
3
4486
by: 100grand | last post by:
Modify the Inventory Program to use a GUI. The GUI should display the information one product at a time, including the item number, the name of the product, the number of units in stock, the price of each unit, and the value of the inventory of that product. In addition, the GUI should display the value of the entire inventory, the additional attribute, and the restocking fee. Here is my Inventory program from 1 to 3: package...
0
10210
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8869
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3956
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.