2011-08-31 50 views
0

我如何在類B函數C中運行方法$ this-> ob-> getVar()?我不知道。我是否必須將字符串傳遞給構造函數?A類和B類之間的傳輸變量

<?php 


class A{ 

    public $tabb = array('1'=>'one', '2'=>'two'); 
    public $index; 

    public function setVar($v){ 

    $this->index = $v; 

    } 

    public function getVar(){ 

    return $this->index; 

    } 

    public function arr(){ 

    return $this->tabb; 

    } 

} 


class B{ 

    public $tab; 

    public function __construct($var){ 

    $this->ob=new A; 

    $this->tab = $var; 

    } 

    public function C(){ 

    return $this->D($this->tab, $this->ob->getVar()); 

     } 

    public function D($l, $j){ 

    if(is_array($l) && isset($j)){ 

     print 'yes'; 

    } else { 

    print 'no'; 

    } 

    } 

} 

$obb = new A; 
$obb->setVar('onetwo'); 
$k = $obb->arr(); 
$obbb = new B($k); 
$obbb->C(); 


?> 
+0

只需在該方法中調用'$ this-> ob-> getVar()'。這段代碼是完全有效的 – zerkms

+0

相同的效果只有數組傳輸的構造函數 – xyz

回答

1

首先,公約的緣故您的B級應申報的$ OBJ私有變量,但是這是沒有必要的PHP。

其次,你的B類只是在其構造函數中創建一個新的A實例。所以你有兩個不同的A類。 B裏面的內容永遠不會擁有其索引屬性。

如果你想有B對象之外創建了一個對象,你必須通過它在這樣的:

$obbb = new B($k, $obb); 

所以,現在你的新型B的構造是這樣的:

public function __construct($var, $someObject){ 

    if (!empty($someObject)) { 
     $this->ob = $someObject; 
    } 
    else { 
     $this->ob=new A; 
    } 

    $this->tab = $var; 

} 
+0

謝謝我可以使用引用,繼承這裏,getInstance方法? – xyz

+0

這項工作,但我仍然從構造函數轉移我的變量;) – xyz

+0

我將學習另一種方法 – xyz