我正在尝试制作Spell
s的数组。
我当前的代码
class Spell
{
public $bomb = 0;
public $fire = 0;
function Spell()
{
$this->bomb =0;
$this->fire =0;
}
}
我在这个游戏类中声明了对象拼写
class game
{
public $Spell=array();
function Game()
{
$this->Spell[0] = new Spell();
}
function s()
{
$this->Spell[1]->$bomb = $load($x)
$this->Spell[1]->$fire = $load($x);
$this->Spell[2]->$bomb = $load($y)
$this->Spell[3]->$bomb = $load($z)
}
}
它会返回此错误 - Warning: Creating default object from empty value in...
我想这不是创建对象数组的最佳方法。怎么做得好?
编辑: x y z,只返回字符串
答案 0 :(得分:0)
问题是你没有为$ this-> Spell [1],$ this-> Spell [2]和$ this-> Spell [3]创建对象。如果您将Game()构造函数更改为:
function Game()
{
for ($i = 1; $i <= 3; $i++) {
$this->Spell[$i] = new Spell();
}
}
应该可以正常工作。
答案 1 :(得分:0)
您的代码中似乎只有一个问题。 但是,我将讨论您提出的问题。 而不是
$this->Spell[1]->$bomb = something;
使用
$this->Spell[1]->bomb = something;
其次,使用$ load($ y)打算做什么?
如果您使用的是名为“load”的函数,请使用load($ y)
答案 2 :(得分:0)
你必须创建对象,然后使用它,看看:
class Spell
{
public $bomb = 0;
public $fire = 0;
function __construct()
{
$this->bomb =0;
$this->fire =0;
}
}
class game
{
public $Spell=array();
function s()
{
$this->Spell[1] = new Spell();
$this->Spell[1]->bomb = 0 ; //or other value
}
}
答案 3 :(得分:0)
<?php
class Spell
{
public $bomb = 0;
public $fire = 0;
function Spell()
{
$this->bomb =0;
$this->fire =0;
}
}
class game
{
public $Spell=array();
function Game($index)
{
$this->Spell[$index] = new Spell();
echo 'constructer called';
}
function s()
{
$this->Spell[1]->bomb = $load($x);
$this->Spell[1]->fire = $load($x);
$this->Spell[2]->bomb = $load($y);
$this->Spell[3]->bomb = $load($z);
}
}
$ob = new game();
//$ob->Game(1); to pass the index for array.
&GT;
答案 4 :(得分:0)
你正在使用大量未定义的东西,我会说你的一半脚本丢失了。 我刚刚在这里添加了评论:
class game
{
public $Spell=array();
function Game()
{
$this->Spell[0] = new Spell();
}
function s()
{
/**
down here you are using these undefined "variables":
$bomb
$load
$x
$y
$z
undefined means, you are using a varible which was not declared. so it´s just null.
I tried to fix it:
**/
$x = 1;
$y = 2;
$z = 3;
$this->Spell[1] = new Spell();
$this->Spell[2] = new Spell();
$this->Spell[3] = new Spell();
$this->Spell[1]->bomb = load($x); // add ;
$this->Spell[1]->fire = load($x);
$this->Spell[2]->bomb = load($y)
$this->Spell[3]->bomb = load($z)
}
}
function load($v)
{
return $v * 2;
}