1

我有一个类创建另一个类的实例。第二个类是否可以从调用类中检索参数。

例如

Class_A {
    protected $myArray = array('item 1', 'item2', 'item3')

    public function __construct()
    {
        $nextClass = new ClassB();
        echo $nextClass->countArrayItems();
    }
}

Class_B {
    public function countArrayItems()
    {
        return count(Class_A->myArray);
    }
}

$newClass = new Class_A;
4

2 回答 2

3

您可以将对您的Class_A实例的引用传递给您的Class_B构造函数:

Class_A {
    public $myArray = array('item 1', 'item2', 'item3')

    public function __construct()
    {
        $nextClass = new Class_B($this);
        echo $nextClass->countArrayItems();
    }
}

Class_B {
    public function __construct($classA_instance) {
        $this->classA_instance = $classA_instance;
    }
    public function countArrayItems()
    {
        return count($this->classA_instance->myArray);
    }
}

$newClass = new Class_A;

(正如@chris 所说,Class_A->myArray 需要公开)

于 2012-06-03T21:03:04.087 回答
1

仅当您将 A 类的实例传递给 B 类时

Class_A { 
    protected $myArray = array('item 1', 'item2', 'item3') 

    public function __construct() 
    { 
        $nextClass = new ClassB(); 
        echo $nextClass->countArrayItems($this); 
    } 
} 

Class_B { 
    public function countArrayItems($callingClass) 
    { 
        return count($callingClass->myArray); 
    } 
} 


$newClass = new Class_A; 
于 2012-06-03T21:03:38.610 回答