我希望我的PHP IDE(NuSphere PhpEd)检测我的2D数组元素(一个对象)的属性,在我的IDE中输入右箭头后,该属性的属性没有显示。
在PHP 7中是否有任何方法可以自动生成多维数组元素属性的建议,其中每个元素都是具有特定属性的对象?
<?php
class Cell
{
private $color;
public function __construct()
{
$this->color = "red";
}
public function __get($propertyName)
{
if ($propertyName == 'color')
return $this->color;
}
public function __set($propertyName, $value)
{
if ($propertyName == 'color')
$this->color = $value;
}
}
class Matrix implements ArrayAccess
{
private $matrix = array();
public function __construct($maxX, $maxY)
{
$this->matrix = array_fill(1, $maxX, array_fill(1, $maxY, null));
}
public function &offsetGet($name)
{
return $this->matrix[$name];
}
public function offsetSet($name, $value)
{
$this->matrix[$name] = $value;
}
public function offsetExists($name)
{
return isset($this->matrix[$name]);
}
public function offsetUnset($name)
{
unset($this->matrix[$name]);
}
}
$matrix = new Matrix(3,3);
for ($xIdx = 1; $xIdx <= 3; $xIdx++)
for ($yIdx = 1; $yIdx <= 3; $yIdx++)
$matrix[$xIdx][$yIdx] = new Cell();
$matrix[2][2]->color = "green";
echo $matrix[2][2]->color;
?>
答案 0 :(得分:2)
如果您乐意使用phpdoc注释,则可以使用Type[][]
注释将变量声明为Type
的2D数组。对于类属性,如下所示:
/** @var Cell[][] */
private $matrix = [];
或者类方法的返回值:
/**
* @return Cell[][]
*/
public function getMatrix() {
return $this->matrix;
}
在PHPStorm的情况下,提供了这个:
答案 1 :(得分:0)
我尝试了一种解决方法,以强制phpdoc按照箭头选择我的属性或方法。
这就是我所做的。
class Matrix
{
protected $maxX;
protected $maxY;
private $matrix = array();
public function __construct($maxX, $maxY)
{
$this->maxX = $maxX;
$this->maxY = $maxY;
$this->matrix = array_fill(1, $maxX, array_fill(1, $maxY, 0));
return $this;
}
public function getMaxX()
{
return $this->maxX;
}
public function getMaxY()
{
return $this->maxY;
}
public function get($x, $y)
{
if (isset($this->matrix[$x][$y]))
return $this->matrix[$x][$y];
throw new OutOfBoundsException("Array at indices $x, $y is out of bounds!");
}
}
class Main
{
public function __construct()
{
}
public function setArrayVal($x, $y)
{
$cell = new Cell();
//Set Value in some arbitrary method in Main Class
$this->matrix($x, $y)->set($cell);
//Or if $val is public in Cell class
// $this->matrix($x, $y)->val = $cell;
}
//Method of Main Class
public function matrix($x, $y) : Cell //Note Cell here specified for type hinting
{
//Note, matrix below is a property, not method, whose type corresponds to the matrix class
return $this->matrix->set($x, $y);
}
}
class Cell
{
private $val;
public function __construct()
{
}
// Method set in Cell class
public function set($val)
{
$this->val = $val;
}
}