2012-10-10 93 views
2

這是我的第二個問題,即使我認爲,我自己回答了前一個問題。無論如何,我有一個關於OOP的基本問題,關於如何從另一個類調用非靜態方法。例如: 我們在一個文件中的類命名爲A A.class.php如何從另一個類中調用非靜態方法

class A { 

    public function doSomething(){ 
    //doing something. 
    } 

} 

,並在另一個文件中的第二類稱爲b B.class.php

require_once 'A.class.php'; 

class B { 

    //Call the method doSomething() from the class A. 

} 

我認爲現在是clearn 。如何:從類A調用方法doSomething()?

回答

0

您需要實例類A的對象只能做B類的方法裏面

class B{ 
    public function doSomethingWithA(){ 
      $a = new A(); 
      return $a->doSomething(); 
     } 

    } 
4

B類需要一個類的對象調用方法上:

class B { 
    public function doStuff() { 
     $a = new A(); 
     $a->doSomething(); 
    } 
} 

或者,您可以創建B的外面的實例,並傳遞到B的構造函數來創建一個全局引用它(或者將它傳遞給一個個體的方法,你的選擇):

class B { 
    private $a = null; 
    public function __construct($a) { 
     $this->a = $a; 
    } 
    public function doStuff() { 
     $this->a->doSomething(); 
    } 
} 

$a = new A(); 
$b = new B($a); 
+0

很簡單,謝謝! – Be0wulf

+0

@MohamedAdibErrifai沒問題,希望它有幫助! – newfurniturey

+0

我的帖子不錯的副本 – JvdBerg

0
class B { 

    public function __construct() 
    { 
     $a = new A; 
     $a->doSomething(); 
    } 


} 
2

如何注入類A到B,使乙依賴A.這是依賴注入的最原始的形式:

class A 
{  
    public function doSomething() 
    { 
    //doing something. 
    } 
} 

class B 
{ 
    private $a; 

    public function __construct(A $a) 
    { 
    $this->a = $a; 
    } 

    //Call the method doSomething() from the class A. 
    public function SomeFunction() 
    { 
    $this->a->doSomething(); 
    } 
} 

此構造是這樣的:

$a = new A(); 
$b = new B($a); 
0

我知道這是一個古老的問題,但考慮到我今天發現它,我想我會爲@newfurniturey的答案添加一些內容。

如果要保留A級內獲得B類,這是我做過什麼:

class A 
{  
    private $b = null 
    public function __construct() 
    { 
     $this->b = new B($this); 

     if (!is_object($this->b) { 
      $this->throwError('No B'); 
     } 

     $this->doSomething(); 
    } 

    public function doSomething() { 
     $this->b->doStuff(); 
    } 

    private function throwError($msg = false) { 
     if (!$msg) { die('Error'); } 
     die($msg); 
    } 
} 

class B { 
    public function doStuff() { 
     // do stuff 
    } 
} 

這種構造是這樣的:

$a = new A(); 
相關問題