scope of class atts in methods
| From: | Erik Price | Date: | Thu, 06 Jun 2002 19:11:40 +0000 |
| Subject: | scope of class atts in methods | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-101003@lists.php.net to get a copy of this message | ||
Hi all,
a quick question about using PHP's objects, specifically in terms of the scope of class attributes:
Normally, in PHP, a variable in a function is local to that function and is NOT a reference to a similarly-named variable outside the function, right? To the best of my knowledge, there are several ways to allow access to an outside variable from within a function:
1) Declare the variable as global with the "global" keyword
2) Access it from the $GLOBALS array
3) Pass the variable to the function as a parameter
and probably others, but it's really beside the point because I don't have a question about normal functions. What I am really wondering is if there is any formal "rules" about the scope of Class Attributes in Class definitions and in methods -- they do not behave identical to PHP's functions. For instance, I can access a class attribute from within a method of that class without explicitly declaring that attribute global inside the method, or without explicitly passing that attribute as a parameter to the method. So they seem to behave as if they are always global.
But if I want to make a change to that class attribute from within a method, am I affecting a copy of the class attribute, or the class attribute itself? The reason I ask is because I have a Class that is behaving oddly. Here is the relevant part of the code:
Class Folder
{
// declare class attributes
var $contents = array();
// a method to add to $contents
function add_to_contents($item)
{
$this->contents[] = $item;
}
// a method to remove from $contents
function rm_item($index)
{
unset($this->contents[$index]);
}
}
The crux of my question is, does this have the effect that it appears to have? I am hoping someone with thorough understanding of the internals of PHP can give me a definitive answer. My tests are coming up with strange results, so I haven't figured it out on my own yet.
Thanks in advance,
Erik
PS: FYI, if you unset an array element, there is still an index for that element -- the array does not reindex itself. A good solution to this, that a fellow lister named Nathan gave me, is to array_push() a dummy var onto the end of the array and then array_pop() it back off -- this reindexes the array. But I am finding that somehow my arrays are "remembering" old elements that I could have sworn I unset, so I am asking the above question about the scope of class attributes in methods.
----
Erik Price
Web Developer Temp
Media Lab, H.H. Brown
pricee@hhbrown.com