2017-07-25 121 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