Php 在类中定义变量
我是PHP新手,我得到了未定义的变量Php 在类中定义变量,php,Php,我是PHP新手,我得到了未定义的变量$firstDect,即使它已定义: class Deck { public function getdeck() { $firstDeck = new Deck(); return $this->firstDeck; } } 以及 getImage();?>"> 阅读的更多信息如果出现错误,请使用以下命令: public function getdeck() {
$firstDect
,即使它已定义:
class Deck
{
public function getdeck()
{
$firstDeck = new Deck();
return $this->firstDeck;
}
}
以及
getImage();?>">
阅读的更多信息如果出现错误,请使用以下命令:
public function getdeck()
{
$firstDeck = new Deck();
return $firstDeck ->firstDeck;
}
$这与self类相关。使用以下类:
class Deck
{
public $firstDeck;
public function getdeck()
{
$this->firstDeck = new Deck();
return $this->firstDeck;
}
}
您已经在函数本身中定义了变量
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;
}
}
或
您可以像这样在类级别定义变量
public function getdeck()
{
$firstDeck = new Deck();
return $firstDeck;
}
class Deck
{
private $firstDeck;
public function getdeck()
{
$this->firstDeck = new Deck();
return $this->firstDeck;
}
}
保留字
$this
是对您当前所在类的对象的引用。因此$this->firstDeck
表示您有一个名为$firstDeck
的类成员,而您没有
您可以在类中将其声明为成员
class Deck
{
private $firstDeck;
public getdeck() { ... }
}
或者你只是写信
public getdeck()
{
$firstdeck = new Deck();
return $firstdeck;
}
很多事情都错了 您正在尝试使用函数中定义的变量 我想你想做的是:
class Deck{
public function getDeck(){
return array(card1, card2...);
}
}
$firstDeck = new Deck();
这就留下了一些未定义的问题,关于什么是卡片或其他超出问题范围的东西
另一方面,我使用了一个数组来确保
getDeck
方法的输出是可移植的,但我认为有一些方法可以使类本身可移植,您只需在文档中查找即可。您在对象内部创建对象是否有特定的原因?我投票结束这个问题,将其作为主题b因为你应该从阅读手册开始:对downvote的反馈总是很感激的。