PHP OOP problem

Saulyx

Junior Member
Joined
Jan 10, 2010
Messages
107
Reaction score
5
Hey everyone, so I have this problem when im coding my bot.

Its PHP, OOP, have several public functions and one of them is getting rather large, the function creates a new object, and assigns it to a variable, variable name is generated from array

${$array[$pocket][0]} = new blah();

now when I do that, its fine because its all one big function, however if I want to divide this into small functions, I cant access these variables from other functions, im guessing because I dont import them as globals, but how do I import them as globals? hope thats quite explanatory, heres quick mock up of what im trying to do


PHP:
class test {

public function connect () {

foreach($this->accs as $key => $value) {

${$value[$key][0]} = new whatever();


}


}

public function post () {

foreach($this->accs as $key => $value) {
//this wont work... 
${$value[$key][0]}->post();


}


}

}


just a quick mock up...
 
What about just declaring it with
PHP:
global $array;
in each function before you try to use it?
 
but will that work? I have the array as a variable for the whole object, but what I cant access is the variables(made from array) in second function
 
Maybe the code below solves your problem. Please let me know...

PHP:
<?php

class test {

        public $accs = array('poster1'=>'joe','poster2'=>'superman');
        public $data = array();

        public function connect () {
                foreach($this->accs as $key => $value) {
                        echo "Assign: $key => $value\n";
                        $this->data[$key][$value] = new whatever();
                }
        }

        public function post () {
                foreach ($this->data as $arr) {
                        foreach ($arr as $poster => $obj) {
                                echo "$poster is posting...\n";
                                $obj->post();
                        }
                }
        }
}

class whatever {
        public function post() {
                echo "posting...\n";
        }
}

$test = new test;

$test->connect();
$test->post();

?>
 
daltarak thats sort of thing i did, but doesnt let me..

also its variable variables so $$name, in my case the $name is an array value


Thanks tho
 
In your code you're creating dynamic arrays in a function, then you're trying to access those variables from another function which is not possible because you didn't declared them as "public", besides you can't declare such dynamic variables outside.

To accomplish your needs I just stored those dynamic data in a pre-declared public array this way you're able to access them from another function. Doesn't it help you really?
 
I see what you mean, so an array 'pocket' can have an object in it? I think its me just being thick now, ill try it out and see, thanks
 
Thats right, just try to run my code you'll see it works! :) Good luck!
 
Back
Top