2017-07-25 119 views
0

我是新來的PHP類,和我越來越不確定的變量$firstDect即使它被定義:定義變量

class Deck 
{ 
    public function getdeck() 
    { 
     $firstDeck = new Deck(); 
     return $this->firstDeck; 
    } 
} 

,並

<div class="panel-body"> 
    <?php foreach ($firstDeck->getDeck() as $card): ?> 
     <img class="col-md-3" src="<?php echo $card->getImage(); ?>"> 
    <?php endforeach; ?> 
</div> 
+0

是否有一個特定的原因,你爲什麼要在自己創建對象? – IsThisJavascript

+1

我投票結束這個問題作爲題外話,因爲你應該從閱讀手冊開始:http://php.net/manual/en/language.oop5.basic.php –

回答

1
class Deck 
{ 
    /* You have to define variable something like below before 
     accessing $this->firstDeck 
    */ 
    public $firstDeck; 


    public function getdeck() 
    { 
     $this->firstDeck = new Deck(); 
     return $this->firstDeck; 
    } 
} 

從閱讀更多Here

-1

您有錯誤,請使用此:

public function getdeck() 
    { 
     $firstDeck = new Deck(); 
     return $firstDeck ->firstDeck; 
    } 

$這與自我班有關。

1

使用下面的類:

class Deck 
    { 
     public $firstDeck; 
     public function getdeck() 
     { 
      $this->firstDeck = new Deck(); 
      return $this->firstDeck; 
     } 
    } 
1

你定義的函數本身的變量。

public function getdeck() 
     { 
      $firstDeck = new Deck(); 
      return $this->firstDeck; 
     } 

你不能在函數內部聲明的變量使用$this$this用於引用在類級別聲明的變量。你可以重寫你的函數是這樣,

public function getdeck() 
     { 
      $firstDeck = new Deck(); 
      return $firstDeck; 
     } 

可以定義在類級別這樣的變量,

class Deck 
    { 
     private $firstDeck; 
     public function getdeck() 
     { 
      $this->firstDeck = new Deck(); 
      return $this->firstDeck; 
     } 
    } 
0

保留字$this是的對象的引用因此$this->firstDeck表示您有一個名爲$firstDeck的班級成員,您沒有這個班級成員。

你要麼在你的類中聲明爲成員

class Deck 
{ 
    private $firstDeck; 
    public getdeck() { ... } 
} 

,或者你只是寫

public getdeck() 
{ 
    $firstdeck = new Deck(); 
    return $firstdeck; 
} 
-1

很多事情都是錯誤的。

您正在嘗試使用函數中定義的變量。

我認爲你正在試圖做的是:

class Deck{ 
    public function getDeck(){ 
     return array(card1, card2...); 
    } 
} 

$firstDeck = new Deck(); 

這留下什麼卡或者是其他的東西,這是超出範圍的問題,一些不確定的問題。另一方面,我使用了一個數組來確保getDeck方法的輸出是可迭代的,但我認爲有辦法讓你的類可以自己迭代,你只需要在文檔中查找。

+0

反饋與downvote去總是讚賞。 – bracco23