Php致命错误:无法在/srv/www/default/work/index.php第30行通过引用传递参数1


Php Fatal error: Cannot pass parameter 1 by reference in /srv/www/default/work/index.php on line 30

我有一个项目,我需要做一个骰子滚子类。类是带有私有成员变量的公共类,而公共成员函数只能修改成员变量。构造函数接受一个参数,该参数是要滚动的骰子的最大面数,以防这个类以后用于非六面骰子滚动。它会在标题中抛出错误,我不知道如何修复这个错误。此外,如果我只是按值传递私有变量给成员函数,它不会维护变量的值。

<?php
/*
 * The base code of the webGames.
 * This file has the classes for cards and dice
 * version 1.0
 * file gamesLib.php
 * build date 6/25/2015
 *
 * To run this library use an include statement to include the file,
 * or download the whole library package and run it all.
 *
 */
class GameDie
{
   private $dieRollValue = 0;
   const MINIMUM_DIE_SIDES = 1;
   private $maxDieSides = 2;
   public function __construct( &$initialMaxDieSides)
   {
        if (is_int ($initialMaxDieSides))
       {
           $maxDieSides = $initialMaxDieSides;
           unset($initialMaxDieSides);
           $this->setDieRoll();
       }
       else
       {  
           print '<script language="javascript">';
           print 'alert("Function: gamesLib did not correctly set a max die side value in the constructor.")';
           print '</script>';
        }
   }
   public function setDieMaxSides( &$passedDieMaxSidesValue)
   {
       if (is_int ($passedDieMaxSidesValue))
       {
           $maxDieSides = $passedDieMaxSidesValue;
           unset($passedDieMaxSidesValue);
       }
       else
       {  
           print '<script language="javascript">';
           print 'alert("Function: gamesLib did not correctly set a max die side value in setDieMaxSidesValue.")';
       print '</script>';
        }
   }
    public function getDieRoll()
    {
        $this->$dieRollValue;
    }
    public function setDieRoll()
    {
        $this->$dieRollValue = (mt_rand(GameDie::MINIMUM_DIE_SIDES, $maxDieSides));
    }
}
$onlyDie = new GameDie(6); 
print ($onlyDie->getDieRoll()); 
?>

错误在构造函数中:

public function __construct( &$initialMaxDieSides)

错误发生是因为您试图将数字6传递给期望变量的构造函数。当你使用&在参数1之前,它说通过引用传递。数字6只是一个值,没有引用。您可以通过使构造函数接受没有引用的变量(public function __construct( $initialMaxDieSides))或进行函数调用来纠正此问题:

$number = 6;
$onlyDie = new GameDie($number);

当你传递GameDie($number)时,$number是一个变量,可以通过引用传递。

这将解决您的第一个问题,但您的代码中还有其他几个问题....但这是作业,所以我会让你自己解决。:)