Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

does "sub" exsits in php? 1

Status
Not open for further replies.

lvennard

MIS
Apr 20, 2000
93
US
im not a native programer but the little bit i do know is that you can use a "sub routine" to change main variables. you use a "function" by passing variables to it and then returning the results.

i just hate passing all of these variables over to the function.

here is a small example

function $do_it($a, $b, $c, $d, $e, $f, $g)
{
if ($a >= $c) { do this; }
}

sub $do_it()
{
if ($a >= $c) { do this; }


i just dont want to pass the variables every time.

Suggestions?
 
i think i just found a way.

function do_it ()
{
global $a, $b, $c, $d;
do somethking here;
}

but , i still hate it.

 
that is exactly it.

chad. ICQ: 54380631
online.dll
 
There is another useful thing to know related to variables and variable scope:

Often PHP programmers like to include() a central config file to place all the "application-level" variables, something like:

Code:
<?php
$hostname = &quot;[URL unfurl="true"]www.thiswebsite.com&quot;;[/URL]
$mysql_user = &quot;myusername&quot;;$mysql_passwd = &quot;mypassword&quot;;
$mysql_db = &quot;mydatabasename&quot;;
?>

Then you just include this page at the top of every PHP file and you only have to change your password or databasename in one place, instead of every page. So far this is standard stuff everyone knows. The only problem is, these shouldn't be variables, they should be constants. (
Constants are a much better choice for this kind of data for several reasons:

1) they automatically have global scope, so you can use them inside any function or code block, without using the &quot;global&quot; keyword.

2) once defined, a constant is unchangeable by the script, so there is no chance of a &quot;cracker&quot; messing with that variable by playing with URL parameters.

3) They use less system resources than regular variables, because the system does not need to track their changes.

Thus the code I show above should actually look like:

Code:
<?php
define (&quot;HOSTNAME&quot;, &quot;[URL unfurl="true"]www.thiswebsite.com&quot;);[/URL]
define (&quot;MYSQL_USER&quot; = &quot;myusername&quot;);
define (&quot;MYSQL_PASSWD&quot; = &quot;mypassword&quot;);
define (&quot;MYSQL_DB&quot; = &quot;mydatabasename&quot;);
?>
Constants do not have to be in all capitals, but that is the recommended usage, for code readability. You don't use the &quot;dollar sign&quot; notation, but just bare text:

mysql_connect(HOSTNAME, MYSQL_USER, MYSQL_PASSWD);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top