-1

我的代码中有这两个错误:

注意:未定义变量:第 61 行 C:\Program Files (x86)\Zend\Apache2\htdocs\ttt.php 中的 p1

注意:尝试在第 61 行的 C:\Program Files (x86)\Zend\Apache2\htdocs\ttt.php 中获取非对象的属性 轮到:

相关代码在这里:

//this is within the Board object
function updateBoard(){ 
    if($this->xTurn == True){
        echo "It is " . $p1->username . "'s turn: "; //line 61
    } elseif($this->xTurn == False){
        echo "It is " . $p2->username . "'s turn: ";
    }
}

//This is within the Player object
function __construct($name){
    $this->username = $name;
}

$a   = new Board();
$p1  = new Player($name);
$p2  = new Player($name);
$new = new Game();
$a->updateBoard

每当我运行它时,它都不会回显 $p1->username。关于如何解决这个问题的任何想法,因为我现在不知道。

更新:哎呀。我遗漏了一些重要的代码。

4

2 回答 2

1

更新板在函数内部没有$p1或没有$p2声明,因此它们不存在。您需要将玩家对象传递给棋盘构造函数,使用 setter 方法设置它们或将它们传递给该updateBoard方法。前两个选项意味着您必须在将对象分配给这些属性之后$this->p1更改它们。$this->p2

function updateBoard($p1, $p2){ 
    if($this->xTurn == True){
        echo "It is " . $p1->username . "'s turn: "; //line 61
    } elseif($this->xTurn == False){
        echo "It is " . $p2->username . "'s turn: ";
    }
}

$a   = new Board();
$p1  = new Player($name);
$p2  = new Player($name);
$new = new Game();
$a->updateBoard($p1, $p2);

http://php.net/manual/en/language.variables.scope.php

于 2013-07-12T13:13:08.037 回答
0

这与您错过的代码完美匹配:-

class Player
 {
var $username;
function __construct($name){
       $this->username = $name;
      }
 }
$name='rajeev ranjan';
$p1  = new Player($name);
echo $p1->username;
于 2013-07-12T04:33:50.963 回答