未定义的变量:

时间:2013-07-12 04:25:53

标签: php variables undefined

我的代码中出现了这两个错误:

  

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

     

注意:尝试在C:\ Program Files中获取非对象的属性   第61行的(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->用户名。关于如何解决这个问题的任何想法,因为我现在还不知道。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

class Player
 {
var $username;
function __construct($name){
       $this->username = $name;
      }
 }
$name='rajeev ranjan';
$p1  = new Player($name);
echo $p1->username;