在类中定义变量

I am new to PHP, and I'm getting undefined variable $firstDect even though it is defined:

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

and,

<div class="panel-body">
    <?php foreach ($firstDeck->getDeck() as $card): ?>
        <img class="col-md-3" src="<?php echo $card->getImage(); ?>">
    <?php endforeach; ?>
</div>
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;
   }
}

Read More from Here

You have an error, use this :

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

$this relate to the self class.

Use following class:

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

You've defined the variable in function itself.

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

You can't use $this with variables declared inside functions, $this is used to reference variable declared at class level. You can rewrite your function like this,

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

or

You can define the variable at class level like this,

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

The reserved word $this is a reference to the object of the class you are currently in. So $this->firstDeck indicates that you have a class member with the name $firstDeck, which you do not have.

You either declare it in your class as a member

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

or you just write

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

A lot of things are wrong.

You are trying to use a variable defined inside a function.

I think what you are trying to do is:

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

$firstDeck = new Deck();

This leaves some undefined questions about what a card is or other stuff which is out of scope on the question.

On the other side, i used an array to assure that the output of the getDeck method is iterable, but i think there are ways to make your class iterable by itself, you just have to look up in the documentation.