Ok, at this point it seems prudent to discuss the issue of "scope". Scope is a major but necessary gotcha in all programming languages, and many of the differences between languages are how they handle scope.
Scope refers to the variables visible to the currently running code. We say a variable is "in scope" if it can be accessed. If it can't, it's not in scope. A variable can share a name with a variable that's not in scope.
Scope is a nuisance in small projects and the temptation is to use the global keyword to bring a variable into the scope of the function. The problem is this makes the function dependent on that variable and it becomes difficult to impossible to test the function in a large project. The solution is simple - don't use global.PHP Code:
$a = 4;
function foo() {
$a = 3;
return $a;
}
echo $a; // 4
echo foo(); // 3
echo $a; // 4.
If a function needs to "see" a value then it should receive it as an argument.
But what if a function does need to work with a lot of values? Passing more than two arguments rapidly becomes cumbersome as you have to remember the order you are passing the values as they will have an impact on the output.PHP Code:function increment( $a ) {
$a++;
return $a;
}
The solution to this problem is the next step of code organization -- Classes and object oriented programming. Once you get used to functions they are the next step. This is the next step up from basic functions - but what classes do is bind functions together with data (and much more, but trying to keep things basic here). When a function is part of a class it is called a "method". When a variable is part of a class it is called a "member" Methods can see the members of the class using the reserved $this value.
I'll stop there because that's the next step beyond functions and I don't want to muddle the issue too much. The point is to show where the road ahead is going.




Reply With Quote


Bookmarks