可以';t从类方法将值写入全局PHP数组


Can't write values into a global PHP array from a class method

PHP不是我的强项,但我今天已经在其中尝试了一些OO代码。除了全局级别的$replyArray数组不是由solSet对象的混乱()类方法编写之外,一切都很好。我的代码中倒数第二个var_dump显示了一个空数组。我试过在全球范围内搜索关键词,但没有起到任何作用。因为我通过引用新实例化的类来显式地传递这个变量,这难道还不够吗?谢谢kk

<?php

//create a solution set for translation of incoming user login requests
$widhi = 600;
$tileDim = 25;
$randArray = array ("0","1","2","3","4","5");
$replyArray = array ();

//create 5 positions and ensure neither overlap or edge collision
class solSet
{
  var $pos1;
  var $pos2;
  var $pos3;
  var $pos4;
  var $pos5;
  var $pos6;

  public function jumble($wh,$ts,$arrShuf,$reply)
  {
    foreach($this as $key => $value)
    {
      $newX = rand (($ts/2),$wh - ($ts/2));
      $newY = rand (($ts/2),$wh - ($ts/2));
      $randNo = array_pop($arrShuf);
      $value = "" . $newX . "_" . $newY . "_" . $randNo;
      $this->$key = $value;
      //push coords onto an array for later ajax
      $pushElem = "" . $newX . "_" . $newY;
      $reply[] = $pushElem;
    }
  }
}

//scramble the random number array for later popping
shuffle($randArray);
//make a solution object
$aSolSet = new solSet;
$aSolSet->jumble($widhi,$tileDim,$randArray,$replyArray);
//store it in a session
session_start();
$_SESSION["solSet"] = $aSolSet;
echo var_dump($replyArray);
echo json_encode($aSolSet);
?>

这似乎与以下内容有关:在类中使用全局数组但这就是我所做的。此外,全世界和他的狗都在说,全球关键词是"做错了"。该怎么办?

您的jumble方法需要引用$replyArray-默认情况下,PHP函数按值操作,这意味着它们对变量的副本进行操作,而不是修改它。请参阅http://php.net/manual/en/language.references.pass.php

更改

public function jumble($wh,$ts,$arrShuf,$reply)

public function jumble($wh,$ts,$arrShuf,&$reply)

变量名称前面的"与"表示参数是通过引用传递的。

或者,您可以简单地返回新的搅乱数组:,而不是从类中更新全局var(不利于重用和可移植性)

public function jumble($wh,$ts,$arrShuf)
{
  $reply = array();
  foreach($this as $key => $value)
    {
      $newX = rand (($ts/2),$wh - ($ts/2));
      $newY = rand (($ts/2),$wh - ($ts/2));
      $randNo = array_pop($arrShuf);
      $value = "" . $newX . "_" . $newY . "_" . $randNo;
      $this->$key = $value;
      //push coords onto an array for later ajax
      $pushElem = "" . $newX . "_" . $newY;
      $reply[] = $pushElem;
    }
  return $reply;
}

并使用以下响应更新您的全局$replyArray

//make a solution object
$aSolSet = new solSet;
$replyArray = $aSolSet->jumble($widhi,$tileDim,$randArray);

然后,您甚至根本不需要将$reply参数传递到方法中(注意,少了一个参数),一切都很好,而且都是自包含的。

引用函数中的全局数组

 global $replyArray;