Re: Help with associative array in a PHP class. Not working as I'd expect it to?!
| From: | Justin Patrin | Date: | Thu, 11 Dec 2003 03:00:32 +0000 |
| Subject: | Re: Help with associative array in a PHP class. Not working as I'd expect it to?! | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-172426@lists.php.net to get a copy of this message | ||
Daevid Vincent wrote:
I'm pulling out my hair on this. I don't think I'm doing anything wrong and I've tried it with PHP 4.3.4 (cli) (built: Nov 7 2003 03:47:25) AND also v4.1.2 on Linux. With the line commented as shown, I get this output: ------You've got a few problems here. That commented line of code is invalid. It is a normal assignment statement, but it is in the class, but not in a function. If you want to initialize a class variable do it in the var statement. var $myPacket = array('blah' => 'asdfasdfasdf'); Or, you can set it in a function (like the costructor) class kismetap { function kismetap() {[daevid=pts/4]6:18pm@dev:{/home/daevid}> ./test.php packetArray:Array ([a] => foo [b] => bar [c] => 1 [d] => 2 [e] => 3) myPacket: ------ How come I don't get ANY array under "myPacket:"? How come I don't get a "[test] => 2345245" under "myPacket:" when I explicitly set it? Uncommenting the 'blah' element causes this error: Parse error: parse error, expectingT_OLD_FUNCTION' orT_FUNCTION' orT_VAR' or'}'' in /home/daevid/test.php on line 16 The 'var' keyword seems to be required, or I get that same error also. I've tried other combinations and can't figure out what I'm doing wrong? ------------------------ snip ----------------- #!/usr/bin/php <?php $PACKET = array('a'=>'foo', 'b'=>'bar', 'c'=>'1', 'd'=>'2', 'e'=>'3'); $AP = array(); $ap['11111'] = new kismetap($PACKET); $ap['11111']->printMyVars(); class kismetap {var $myPacket = array();// $myPacket["blah"] = "asdfasdfasdf";function kismetap( $packetArray ) { echo "packetArray:\n"; print_r($packetArray);$this->myPacket = $packetArray; $this->myPacket["test"] = 2345245;global $myPacket; $myPacket = $packetArray; } //kismetap::constructorfunction printMyVars() { echo "myPacket:\n"; print_r($myPacket); }} //kismetap class ?>
$this->$myPacket = array('blah' => 'asdfasdfasdf');
}
}
Doing
global $myPacket;
is the equivelent of:
$myPacket =& $GLOBALS['myPacket'];
whicks brings the global variable $myPacket into the local namespace of the function. This does NOT export the class variable for global use.
If you want to make the class variable $myPacket the same as the global, in your constructor you could do:
$this->myPacket =& $GLOBALS['myPacket'];
But that's really not a good idea. Why not just do
function printMyVars() {
echo "myPacket:\n";
print_r($this->myPacket);
}
This will give you your expected output.
Please remember ot use globals sparingly as they make very kludgy code.
--
paperCrane <Justin Patrin>