将类的实例传递给另一个类以使用其变量

时间:2015-01-23 16:16:10

标签: php class parameter-passing instance-variables

我正在尝试将我的Generator类的实例传递给另一个类来使用一些变量。 Generator类实例工作正常但是当我将它传递给另一个(SelectStrategy)类时,它似乎根本没有传递变量。我不确定我做错了什么 - 我在被调用函数上使用了var_dump来检查它给了我什么,但它只是空白。

功能

class Generator 
{
    //properties for self
    private $s_charge;
    public $connection;
    public $task_priority;
    public $fog_mode = true;
    public $nodes = array();
    public $type;

    public function generateNodesSpecs() {
        $node = array();

        for ($i = 0; $i < 100; $i++) {

            $charge1 = mt_rand(30,100);
            $node['charge'] = $charge1;
            //array_push($node, $charge1);
            $hops = mt_rand(0,4);
            $node['hops'] = $hops;
            //array_push($node, $hops);
            $resource1 = mt_rand(0,100);
            if ($resource1 <= 50) {
                if ($resource1 <=10){
                    $node['connection'] = '4G';
                    //array_push($node, '4G');
                }
                else {
                    $node['connection'] = '3G';
                    //array_push($node, '3G');
                }
            }
            else if ($resource1 > 50 && $resource1 <= 60) {
                $node['connection'] = 'WiFi';
                //array_push($node, 'WiFi');
            }
            else {
            }
            $resource2 = mt_rand(0,100);
            if ($resource2 <=60) {
                $node['additional'] = 'CPU';
                //array_push($node, 'CPU');
            }
            else {
            $node['additional'] = 'none';
            }
            $this->nodes[] = $node;
            //array_push($nodes, $node);
            unset($node);

        }
    //compare which get the resources
    //var_dump($this->nodes[0]); 
    }
class SelectStrategy {
//take in generator class instance
    private $generator;
    private $priority;
    private $size;
    private $slaves = array();
    private $found_slave = null; //will hold item with max val;
    public function __construct($generator) {
        $this->generator = $generator;
    }
private function selectSlaves() {
        $max = -9999999; //will hold max val
        foreach($this->generator->nodes as $k=>$v)
        {
            if($v['charge']>$max)
            {
               $max = $v['charge'];
               $this->found_slave = $v;
            }
        }

        var_dump($this->found_slave); 

} 
}

和类/函数调用

$generator = new Generator();
$generator->generateNodesSpecs();
$select_strategy = new SelectStrategy($generator);
$select_strategy->selectSlaves();

$this->generator->nodes是一个二维数组

1 个答案:

答案 0 :(得分:0)

global $generator;
在SelectSlave的每个功能中都应该这样做